-   Programming (
-   -   Retrieve numerical values from a text file (

shik28 11-22-2011 12:57 AM

Retrieve numerical values from a text file
1 Attachment(s)
I have to retrieve numbers from a text file which is as shown in the attachment. I have written the following code snippet just to check if I am able to print the numbers in the file.

try {
        Scanner myFile = new Scanner(new FileReader("C:/Documents and Settings/shikhau/workspace/SanNumber/freelast.txt"));
        while (myFile.hasNext()) {
                i = myFile.nextInt();
catch (FileNotFoundException e){
          System.out.println("Sorry! This file is not found");

I get the following exception:

Exception in thread "main" java.util.InputMismatchException
        at java.util.Scanner.throwFor(Unknown Source)
        at Source)
        at java.util.Scanner.nextInt(Unknown Source)
        at java.util.Scanner.nextInt(Unknown Source)

What do I do?

JohnGraham 11-22-2011 02:02 AM

You're getting this exception because you're trying to get an int (with nextInt()) when the next token is not recognised as an integer. Have a look at the docs for Scanner here. In particular, hasNextInt() will let you see if the next token is an int and next() will let you skip any non-int input. Exactly how you want to do that depends on how strict/forgiving you want to be on the format of the configuration file.

All times are GMT -5. The time now is 08:50 PM.