我正在嘗試編寫一個里程跟蹤器程序來跟蹤用戶步行、跑步或游泳的距離。該程序在會話期間要求用戶輸入步行距離,將其存儲在雙精度中,從文件中讀取有關先前步行總距離的數據,將最新會話的距離添加到過去的總距離以創建新的總距離,并將該總數寫入存儲它的文件以供將來使用。編寫代碼時,當我嘗試將它們指向文件時,IDE 在打印寫入器和掃描儀上顯示錯誤:Scanner reader = new Scanner(storage); //error at second ScannerPrintWriter writer = new PrintWriter(storage); // error at second PrintWriter錯誤顯示為“FileNotFoundException”當放置在 try 塊中時,錯誤消失,程序在運行時打印 catch 塊錯誤報告:catch(FileNotFoundException e){ System.out.println("Check that the text file is in the correct directory."); e.printStackTrace(); }這是我使用 PrintWriter 編寫的第一個程序,因此將不勝感激一些指針和關于我做錯了什么的解釋。這是完整的代碼:import java.io.File;import java.io.PrintWriter;import java.io.FileInputStream;import java.util.Scanner;import java.io.IOException;import java.io.FileNotFoundException;import java.lang.String;public class Main { public static void main(String[] args) { //gets interval data from user System.out.println("Please type the amount of miles walked."); Scanner input = new Scanner(System.in); double inMiles = input.nextDouble(); //creates file and scanner that reads to file File storage = new File ("Mile Tracker//Mile.txt"); try { storage.createNewFile(); } catch(IOException e ){ System.out.println("File not created."); } try { Scanner reader = new Scanner(storage); //takes data from file and sets it to a variable double Miles = reader.nextDouble(); double TotalMiles = Miles + inMiles; //PrintWriter reader = new PrintWriter( file ); //PrintWriter that clears the file /*PrintWriter clearwriter = new PrintWriter(storage); clearwriter.print(""); clearwriter.close();*/ PrintWriter writer = new PrintWriter(storage); writer.print(TotalMiles); } }}
1 回答

鴻蒙傳說
TA貢獻1865條經驗 獲得超7個贊
如果您已經有一個名為“Mile Tracker”的目錄,請檢查它是否在 java 類的同一路徑中,因為您沒有明確地為File構造函數提供路徑。如果您沒有“Mile Tracker”目錄,則將代碼修改為:
File storage = new File ("Mile Tracker//Mile.txt");
try {
storage.getParentFile().mkdirs();
storage.createNewFile();
}
catch(Exception e ){
System.out.println("File not created.");
}
從這一點來看,FileNotFound錯誤應該得到解決。
添加回答
舉報
0/150
提交
取消