How to put a Scanner input into an array... for example a couple of numbers
To put input from a Scanner
into an array in Java, you can use a loop to read the input and store it in the array. Here is an example of how you can do this:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Read the size of the array
System.out.print("Enter the size of the array: ");
int size = scanner.nextInt();
// Create an array of the given size
int[] numbers = new int[size];
// Read the numbers and store them in the array
for (int i = 0; i < size; i++) {
System.out.print("Enter a number: ");
numbers[i] = scanner.nextInt();
}
// Print the numbers
System.out.println("The numbers are: ");
for (int number : numbers) {
System.out.println(number);
}
}
}
This code will prompt the user to enter the size of the array, and then read size
numbers from the user and store them in the array. Finally, it will print the numbers.
Here is an example of the program in action:
Enter the size of the array: 3
Enter a number: 1
Enter a number: 2
Enter a number: 3
The numbers are:
1
2
3