亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

打印機 FileNotFoundException

打印機 FileNotFoundException

慕少森 2022-05-25 10:28:43
我正在嘗試編寫一個里程跟蹤器程序來跟蹤用戶步行、跑步或游泳的距離。該程序在會話期間要求用戶輸入步行距離,將其存儲在雙精度中,從文件中讀取有關先前步行總距離的數據,將最新會話的距離添加到過去的總距離以創建新的總距離,并將該總數寫入存儲它的文件以供將來使用。編寫代碼時,當我嘗試將它們指向文件時,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錯誤應該得到解決。


查看完整回答
反對 回復 2022-05-25
  • 1 回答
  • 0 關注
  • 137 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號