[英]Why is my method only reading one line of text?
我有一種方法可以讀取文本文件的一部分,該文件有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");
}
}
編輯:取出最后的工作。
在這里閱讀有關finally
工作原理的詳細信息。 由於您finally
與try/catch
配對,因此您目前正在while
循環的第一次迭代結束時關閉Scanner。 自關閉文件以來, 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");
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.