I write some code to input something and use the while loop to ask repeatedly the input util the empty line. And I also want to split these inputs into some arrays and print the second element of the array. But in this case, I meet ArrayIndexOutOfBoundsException problem.
I guess my error is because when I input space to expect it to break the loop, the program still execute the printing second element of array.
import java.io.*;
import java.util.*;
public class test{
public static void main(String args[]){
Scanner scan=new Scanner(System.in);
while (!scan.nextLine().equals(" ")){
String line=scan.nextLine();
String[] a=line.split(",");
String item=a[1];
System.out.println(item);
}
}
}
And what is expected is when I input "apple,3" it will print "3"; when I input "1, soda", it will print "soda"; and when I input space, the loop will break out. like this:
apple,3
3
1,soda
soda
But the actual is like this:
apple,3
1,soda
soda
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1 at
test.main(test.java:9)