0

I am trying to read a line from a text file in java. I get a java.lang.ArrayIndexOutOfBoundsException: 1 exception.

Here is my code:

try {
    Scanner kb = new Scanner(new FileReader(fileName));
    String line = "";
    int count = 0;
    while (kb.hasNext()) {
        line = kb.next();
        String[] temp = line.split("#");
        System.out.println(temp[1]);
        Wedding tempWed = new Wedding(temp[0], temp[1], temp[2], temp[3], Integer.parseInt(temp[4]));
        test[count] = tempWed;
        count++;
    }
} catch (FileNotFoundException ex) {

}

This is the line in the textfile:
Chiquita Sanford#Magee Sosa#2016-11-05#Garden#84

I need to split by the "#", and this partly works. Java throws the exception when I try to access the element at position 1. I think this is because there is a space between the first name and the surname, because when I System.out.println(temp[0]) it displays "Chiquita" and not "Chiquita Sanford".

Does Java have some restriction on splitting when there are multiple words in the first array index.

Andreas
  • 138,167
  • 8
  • 112
  • 195
keziakoko
  • 155
  • 1
  • 9
  • 3
    Change `kb.next()` to `kb.nextLine()`, and change `kb.hasNext()` to `kb.hasNextLine()`. – Andreas Oct 19 '17 at 19:14
  • 1
    Better yet, don't use `Scanner`, since it is slow. Use `BufferedReader` and its `readLine()` method instead. – Andreas Oct 19 '17 at 19:16

2 Answers2

3

You have to use the nextLine method to read the full line. next will read until the first token ("Chiquita" in your case because its followed by a space character and is interpreted as a delimiter). So change this line:

line = kb.next();

with this:

line = kb.nextLine();
Juan Carlos Mendoza
  • 5,203
  • 7
  • 21
  • 48
2

You are using kb.next() that will return the next word not the next line, for this use kb.nextLine() similar issue with kb.hasNext() needs to be kb.hasNextLine()

Dale
  • 1,821
  • 9
  • 18