gpt4 book ai didi

java - printf 中文件的输出

转载 作者:行者123 更新时间:2023-11-30 05:09:44 24 4
gpt4 key购买 nike

寻求有关以下代码的帮助:

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




}

}

运行程序时出现异常

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)

被抛出。

friends2.dat 是一个数据文件,具有以下内容......

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.

这只是一个文本文件。任何解决输入不匹配问题的帮助都会很棒。谢谢。

最佳答案

编辑:没关系。我误解了输入文件的模式:)

扫描仪在调用String nm = reader.nextLine();时读取完整的行。然后您调用 reader.nextInt(); ,但下一行不以整数开头。因此它会抛出异常。

我认为您应该尝试使用正则表达式(http://download-llnw.oracle.com/javase/6/docs/api/java/util/Scanner.html#next%28java.util.regex。 Pattern%29) 或使用 (http://download.oracle.com/javase/1.4.2/docs/api/java/lang/String.html#indexOf%28java.lang.String%29) 查找正确的部分.

顺便说一句,应该添加作业标签:)

关于java - printf 中文件的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3858829/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com