开发者

Output from a file in printf

开发者 https://www.devze.com 2023-01-18 13:29 出处:网络
Looking for help with the following code: package pkgPeople; import java.io.File; import java.io.FileOutputStream;

Looking for help with the following code:

package pkgPeople;

import java.io.File;
import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Scanner;


public class RetrieveNonSerializedFile {

    public static void main(String[] args) throws Exception{
    File inFile = new File("F:/CS9.27/friends2.dat");

       Scanner reader = new Scanner(inFile);


       while (reader.hasNextLine()){
        String nm = reader.nextLine();
        int height = reader.nextInt();
        int weight = reader.nextInt();
        double balance = reader.nextDouble();
        long acctID = reader.nextInt(开发者_开发百科);

        System.out.println(nm + ":" + height + " inches " + weight + " pounds" + acctID + " account ID" + balance + "dollars");
        /*writer.println(nm);
        writer.println(height);
        writer.println(weight);
        writer.println(acctID);
        writer.println(balance);*/
       }

        reader.close();
        //writer.close();




    }

}

When running the program, the exception

Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at pkgPeople.RetrieveNonSerializedFile.main(RetrieveNonSerializedFile.java:22)

is thrown.

The friends2.dat is a data file that has the following.....

Jim is the name of the person.
13 inches is the height of Jim.
14 pounds is the weight of Jim
1234.650000 dollars is the balance of Jim
12345 is the ID of the bank account.

It is just a text file. Any help to get through the InputMismatch would be great. Thanks.


Edit: never mind. i misunderstood the pattern of the inputfile :)

The Scanner reads on calling String nm = reader.nextLine(); the complete line. Then you call reader.nextInt(); but the next line doesn't start with a integer. Therefore it throws a Exception.

I think you should try to use a regular expression (http://download-llnw.oracle.com/javase/6/docs/api/java/util/Scanner.html#next%28java.util.regex.Pattern%29) or use (http://download.oracle.com/javase/1.4.2/docs/api/java/lang/String.html#indexOf%28java.lang.String%29) for finding the correct parts.

BTW the homework tag should be added :)


You haven't consumed the whole line "13 inches is the height of Jim.", you've read only the "13" part of that line with your int height = reader.nextInt(); When you then try to read the weight (on line 22 according to your traceback) you are trying to read starting at "inches" on the 2nd line of the input file.

0

精彩评论

暂无评论...
验证码 换一张
取 消