3

I am extracting data from a file. I am having trouble with using the delimiters while reading through the file.

My file is ordered like so:

0    Name    0
1    Name1   1

The structure is an integer, a tab (\t), a string, a tab (\t), another integer, and then a newline (\n).

I have tried to use a compound delimiter as referenced in this question: Java - Using multiple delimiters in a scanner

However, I am still getting an InputMismatch Exception when I run the following code:

while(readStations.hasNextLine()) { 
 327    tempSID = readStations.nextInt();
 328    tempName = readStations.next();
 329    tempLine = readStations.nextInt();
        //More code here
}

It calls this error on line two of the above code... I am not sure why, and help would be appreciated, Thanks.

The current output runs as such for the code:

Exception in thread "main" java.util.InputMismatchException
    ...stuff...
    at Metro.declarations(Metro.java:329)
Community
  • 1
  • 1
MLavrentyev
  • 1,629
  • 1
  • 23
  • 31

2 Answers2

2

Newline is most likely causing you issues. Try this

    public class TestScanner {

        public static void main(String[] args) throws IOException {
            try {   
                Scanner scanner = new Scanner(new File("data.txt"));   
                scanner.useDelimiter(System.getProperty("line.separator"));   
                while (scanner.hasNext())  {  
                    String[] tokens = scanner.next().split("\t");
                    for(String token : tokens) {
                        System.out.print("[" + token + "]");
                    }
                    System.out.print("\n");
                }
                scanner.close();  
            } 
            catch (FileNotFoundException e) {   
                e.printStackTrace();  
            }
       }
    }
Constantin
  • 1,418
  • 10
  • 16
  • So I am take each line and storing it in a `String`. Then I split each line. However, even though I have three things, it only splits and gives me two. Why? How can I fix this? – MLavrentyev May 05 '15 at 13:55
  • The file looks like what I showed above in the question (i.e. the `0 Name 0`, etc.). The file is spaced 0 tab String tab 0 – MLavrentyev May 05 '15 at 23:49
  • the example above has several spaces between them ... I used [0][TAB][Name][TAB][0] and it works for me just fine – Constantin May 06 '15 at 00:01
  • Yes... but the Question will not allow a tab character. Those are "tab" characters – MLavrentyev May 06 '15 at 00:03
  • I understand, but I have tested this and it is working ... Can you provide me the output of what it looks like? and also your code – Constantin May 06 '15 at 00:07
  • Maybe you have multiple tabs in between the tokens by accident – Constantin May 06 '15 at 00:17
0

i think when the scanner separates input like this you can only use input.next() not next int: or keep the same type.

Nemo_Sol
  • 342
  • 1
  • 3
  • 16