Home > Back-end >  How to fill an array based on users input in a single line
How to fill an array based on users input in a single line

Time:05-31

I have an array of 3 and want to fill it with users input at once(not to ask for input twice)

Scanner myArray = new Scanner(System.in);
System.out.println("Please R and C with two spaces in between:");
inputs[i] = myArray.nextInt();
R = (inputs[0]);
C = (inputs[3]);

but I am receiving error for assigning C = (inputs[3]);.
How can I fix it?

CodePudding user response:

I’m not sure if what you showed is an abridged version of your code, but here is how to resolve your problem.

Scanner scanner = new Scanner(System.in);
System.out.print("Please R and C with two spaces in between: ");
int R = scanner.nextInt();
int C = scanner.nextInt();

If you absolutely need an array, then do this:

Scanner scanner = new Scanner(System.in);
System.out.println("Please R and C with two spaces in between:");
int[] inputs = {scanner.nextInt(), scanner.nextInt()};
int R = inputs[0];
int C = inputs[1];

Note: the space is skipped unless you use nextLine()

  •  Tags:  
  • java
  • Related