gpt4 book ai didi

java - 为什么我的方法只读取一行文本?

转载 作者:行者123 更新时间:2023-12-02 01:48:01 26 4
gpt4 key购买 nike

我有一个方法可以读取包含 4 个部分的文本文件的各个部分:日期、名称、描述和金额,例如

4/5/2018, gel, hair product, 20.00
4/4/2018, wax, hair product, 20.00

等等...

我的问题是我的方法只会读取第一行,然后输出我的 catch 方法,说找不到该文件。

public static void showRecordedExpense(String filename)throws IOException {
String date = "";
String name = "";
String description = "";
double amount = 0.00;
try{
Scanner read = new Scanner(new File(filename));
while (read.hasNextLine()){
String oneLine = read.nextLine();
String[] parts = oneLine.split(",");
try {
date = parts[0];
name = parts[1];
description = parts[2];
amount = Double.parseDouble(parts[3]);
System.out.printf("%15s%15s%15s%20s%n", "---------------", "---------------",
"---------------", "---------------------");
System.out.printf("%15s%15s%15s%31s%n","Date", "Name", "Description","Amount");
System.out.printf("%15s%14s%33s%15s%n",date,name,description,amount);
System.out.printf("%15s%15s%15s%20s%n", "---------------", "---------------",
"---------------", "---------------------");
}catch (Exception e){
System.out.println("no");
} finally {
read.close();
}
}
}catch (Exception e){
System.out.println("The file could not be found");
}

}

编辑:拿出终于成功的。

最佳答案

阅读here有关 finally 工作原理的详细信息。由于您与 try/catch 配对的 finally,您当前正在 while 循环的第一次迭代结束时关闭扫描程序。自您关闭文件以来, while 的下一次迭代无法再从文件中读取文件,这就是它只读取第一行的原因。考虑在 while 循环完成后取出finally并关闭扫描器。

     try{
Scanner read = new Scanner(new File(filename));
while (read.hasNextLine()){
String oneLine = read.nextLine();
String[] parts = oneLine.split(",");
try {
date = parts[0];
name = parts[1];
description = parts[2];
amount = Double.parseDouble(parts[3]);
System.out.printf("%15s%15s%15s%20s%n", "---------------", "---------------",
"---------------", "---------------------");
System.out.printf("%15s%15s%15s%31s%n","Date", "Name", "Description","Amount");
System.out.printf("%15s%14s%33s%15s%n",date,name,description,amount);
System.out.printf("%15s%15s%15s%20s%n", "---------------", "---------------",
"---------------", "---------------------");
}catch (Exception e){
System.out.println("no");
}
}

read.close();
}catch (Exception e){
System.out.println("The file could not be found");
}

关于java - 为什么我的方法只读取一行文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53456086/

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