I have a method that would read parts of a text file that has 4 parts: date, name, description and amount like
4/5/2018, gel, hair product, 20.00
4/4/2018, wax, hair product, 20.00
and so on...
My problem is that my method would only read the 1st line and then output my catch method saying that the file isn't found.
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");
}
}
EDIT: Taking out the finally worked.
Read here for details on how finally
works. You are currently closing your Scanner at the end of your first iteration of the while
loop due to the finally
you paired with your try/catch
. The next iteration of the while
can no longer read from the file since you closed it, which is why it's only reading the first line. Consider taking out the finally and just closing the Scanner once the while
loop is complete.
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");
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.