猿问

打印机 FileNotFoundException

我正在尝试编写一个里程跟踪器程序来跟踪用户步行、跑步或游泳的距离。该程序在会话期间要求用户输入步行距离,将其存储在双精度中,从文件中读取有关先前步行总距离的数据,将最新会话的距离添加到过去的总距离以创建新的总距离,并将该总数写入存储它的文件以供将来使用。编写代码时,当我尝试将它们指向文件时,IDE 在打印写入器和扫描仪上显示错误:


Scanner reader = new Scanner(storage); //error at second Scanner

PrintWriter 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);

        }


     }

}


慕少森
浏览 186回答 1
1回答

鸿蒙传说

如果您已经有一个名为“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错误应该得到解决。
随时随地看视频慕课网APP

相关分类

Java
我要回答