Search code examples
javajava.util.scannerreadfileinputmismatchexception

Issue with Reading two Int values from a file


I have file with the below data

A,8,43
B,7,42,
C,9,34

I am using the below code to read the data

Scanner input = new Scanner(new File("D:\\test.txt"));
input.useDelimiter(",|\n");  
while(input.hasNext()) {
   String name = input.next();
   int age = input.nextInt();
   int height = input.nextInt();

When I am executing the program I am getting InputMisMatch exception, Please suggest what is mistake.


Solution

  • At end of second line you have , and line separator (I am assuming \n) This means you have empty element between these two delimiters.

    So in third iteration

    String name = input.next();  
    int age = input.nextInt();
    int height = input.nextInt();
    

    input.next(); is consuming "", which means input.nextInt() will try to consume C.

    To solve this problem you can set delimiter to be combination of one or more commas and line separators like

    input.useDelimiter("(,|\n)+");
    

    To improve your code even farther instead of \n you can use \\R added in Java 8 (or \r|\n in earlier versions) to handle all line separators, because currently you don't consider \r as delimiter so it can be treated as valid token.

    So better solution would be using

    input.useDelimiter("(,|\\R)+"); //for readability
    

    or even

    input.useDelimiter("[,\r\n]+");