为了账号安全,请及时绑定邮箱和手机立即绑定

打印机 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 关注
  • 185 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号