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