1

I've just started Java recently. There's an exercise that ask me to split and display the number separated by spacebar. The standard input is basically like this:

2
2 2

The first line is the number of integers in the array. The second line is the array This is the first block of code that I use

   import java.util.*;

/* Name of the class has to be "Main" only if the class is public. */
public class Main
{
    public static void main (String[] args) 
    {
        Scanner reader= new Scanner(System.in);
        int t=reader.nextInt();
        String []s=reader.nextLine().split(" ");
        for(int i=0;i<=t-1;i++)
        {
            System.out.println("The "+(i+1) +" number is "+s[i]);
        }
    }
}

When compile and run it gives me this error

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
    at Main.main(Main.java:15)

However when I change the the reader.nextInt() to reader.nextLine() and parse it into integer it works perfectly fine

import java.util.*;

/* Name of the class has to be "Main" only if the class is public. */
public class Main
{
    public static void main (String[] args) 
    {
        Scanner reader= new Scanner(System.in);
        int t=Integer.parseInt(reader.nextLine());
        String []s=reader.nextLine().split(" ");
        for(int i=0;i<=t-1;i++)
        {
            System.out.println("The "+(i+1) +" number is "+s[i]);
        }
    }
}

This is what the output looks like

The 1 number is 2
The 2 number is 2

So why doesn't it work with reader.nextInt() ?

Edit about the reading the Line character, I still don't get it. It reads the string normally

kjfunh
  • 11
  • 3

1 Answers1

0
int t=reader.nextInt();

Reads a 2.

reader.nextLine()

Reads to the next newline character.

Calling it again will read 2 2, as expected.

Check the content of s. It's likely empty, or doesn't have 2 elements, thus the error

When you read the line twice, you consume the newline

For more info, see Scanner is skipping nextLine() after using next(), nextInt() or other nextFoo() methods

Community
  • 1
  • 1
OneCricketeer
  • 126,858
  • 14
  • 92
  • 185
  • In the first scenario, If I simply change the s into String s=reader.nextLine(), it still shows 2 2 however when split, it is unable to split properly – kjfunh Oct 10 '16 at 14:36
  • You are welcome to post another question with your problem. `"2 2".split(" ")` works for me, though – OneCricketeer Oct 10 '16 at 14:38