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.

2
  • 2
    Try String line=sc.nextLine(); . Commented Mar 9, 2018 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. Commented Mar 9, 2018 at 15:18

3 Answers 3

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;
Sign up to request clarification or add additional context in comments.

1 Comment

In which case you can initialize new String[100][].
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

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.