1

I want to take input as a single line with spaces then enter that data into the two dimensional array.

String[][] examples = new String[100][100];
for (int i = 0; i < 2; i++) {
    System.out.println("enter line " + i);
    String line = sc.next();
    String[] linearr = line.split("\\s+");
    for (int j = 0; j < 5; j++) {
        examples[i][j] = linearr[j];
        System.out.println(linearr[j]);
    }
}

Only the linearr[0] gets value entered ...linearr[1] , linearr[2] , so on do not get values rather says index out of bounds.

myselfmiqdad
  • 2,092
  • 2
  • 13
  • 31
Raja
  • 75
  • 1
  • 1
  • 9
  • 2
    Try `String line=sc.nextLine();` . – Arnaud Mar 09 '18 at 15:16
  • By far the best way to know what's wrong with this code is to use the powerful debugger built into your IDE to step through the code statement by statement, inspecting the contents of variables, etc. Using a debugger is **not** an advanced skill. It's one of the first things any beginner should learn, soon after their first "hello world" program. – T.J. Crowder Mar 09 '18 at 15:18

3 Answers3

2

sc.next() only returns the first word.

sc.nextLine() returns the whole line.

And instead of

for(int j=0;j<5;j++)
{
    examples[i][j]=linearr[j];
    System.out.println(linearr[j]);
}

you can just do

examples[i] = linearr;
Kokogino
  • 774
  • 1
  • 4
  • 16
1

You wanted to receive a line, but your current code only receive a word per input.

Instead of using:

String line=sc.next();        //receive a word

Change it to:

String line=sc.nextLine();    //receive a line

so on dont get values rather says index out of bounds.....

Instead of using 5, the number of String tokens from the split can be used as the loop control for your inner loop, so you may want:

for(int j=0; j < linearr.length; j++)

This will prevent IndexOutOfBoundsException when there are lesser than 5 words in the input.

user3437460
  • 16,235
  • 13
  • 52
  • 96
1

Instead of the sc.next():

 String line=sc.next();

You should use:

String line=sc.nextLine();

Because next() can read input only till space and should be used for only single word.And if you are about to read a line you should use nextLine()

To know more read this

Dheeraj Joshi
  • 1,310
  • 13
  • 23