MLavrentyev
MLavrentyev

Reputation: 1969

Using a scanner to extract data with delimiters by line

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)

Upvotes: 3

Views: 1484

Answers (2)

Constantin
Constantin

Reputation: 1506

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();  
            }
       }
    }

Upvotes: 2

Nemo_Sol
Nemo_Sol

Reputation: 352

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

Upvotes: 0

Related Questions