-2

I am having an error reading a from a .dat file. The .dat file is set up like this:

<Name>/<age>

and I use the / as a delimiter. I am attempting to read from the file to read the name and age, but it comes up with this error:

Exception in thread "main" java.util.InputMismatchException
        at java.util.Scanner.throwFor(Scanner.java:819)
        at java.util.Scanner.next(Scanner.java:1431)
        at java.util.Scanner.nextInt(Scanner.java:2040)
        at java.util.Scanner.nextInt(Scanner.java:2000)
        at Lab04a.input(Lab04a.java:26)
        at Lab04a.main(Lab04a.java:18)
Java Result: 1

The problematic method is this:

public void input() {
        try {
            File dat = new File("Lab04a.dat");
            Scanner sc = new Scanner(dat).useDelimiter("/");
            String name = sc.next();
            int age = sc.nextInt();
            Lab.process(name, age);
        }
        catch(FileNotFoundException e) {
            System.out.println("Missing or corrupted data file.");
            System.exit(0);
        }
    }

The lines giving errors are lines 26 and 18, and these are the lines:

Line 18:

Lab.input();

And line 26:

int age = sc.nextInt();

Line 18 can't have anything wrong, as it only calls the problematic method. Line 26 is (to my best guess) where the error is occurring.

Nick D.
  • 59
  • 5

2 Answers2

0

The line

int age = sc.nextInt();


can give you InputMismatchException if the next token does not match the Integer regular expression, or is out of range

sol4me
  • 15,233
  • 5
  • 34
  • 34
0

try this

Scanner sc = new Scanner(dat).useDelimiter("\\/");

EDIT

import java.io.File;
import java.io.FileNotFoundException;
import java.util.*;

/**
 * @author Davide
 */
public class test {
    static Map map;

    public static void main(String[] args) {
        // init value
        input();
    }


    public static void input() {
        try {
            File dat = new File("test.dat");
            Scanner sc = new Scanner(dat).useDelimiter("\\/");
            String name = sc.next();
            int age = sc.nextInt();
            System.out.println(name + " " + age);
        }
        catch(FileNotFoundException e) {
            System.out.println("Missing or corrupted data file.");
            System.exit(0);
        }
    }

}

dat file

ciao/56

UPDATE

try {
    // ...
} catch (InputMismatchException e) {
    sc.next(); 
}
Davide
  • 622
  • 4
  • 10