Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to fill an array based on users input in a single line

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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()

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading