0

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)
Code Maniac
  • 37,143
  • 5
  • 39
  • 60
An Yan
  • 121
  • 3
  • 11
  • 1
    You're using `nextLine()` twice in a row.. – Yassin Hajaj Mar 24 '19 at 10:01
  • 1
    Consider what your code is doing when there are no commas in the string. What does `line.split(",")` return? What are you doing with what it returns? – T.J. Crowder Mar 24 '19 at 10:01
  • @YassinHajaj so my problem is that I can only nextLine() once? But I wonder how can I break the loop – An Yan Mar 24 '19 at 11:03
  • @T.J.Crowder but in this case when I just only input some strings containing commas it still doesn't work – An Yan Mar 24 '19 at 11:06
  • 1
    AnYan - Yeah, @YassinHajaj put his/her finger on it. By calling `nextLine` twice, you're consuming the input the first time and then using the *next* line in `split`. You're looking for: `String line; while (!(line = scan.nextLine()).equals(" ")) { String[] a = line.split(","); /*...*/ }` – T.J. Crowder Mar 24 '19 at 11:09

0 Answers0