繁体   English   中英

使用PrintWriter时出错

[英]Error when using PrintWriter

我正在尝试编写一个程序,提示用户输入速度和时间。 之后,我需要计算distance = velocity * time 如果用户输入的时间小于零且大于时间,那么我需要重新提示用户。

Hour        Distance Travelled
===========================
1           40
2           80
3           120

例如,如果用户将时间输入为5,则该表应类似于以下内容:

Hour        Distance Travelled
===========================
1           40
2           80
3           120
4           160
5           200

我需要像上面的表格,但是我需要将表格输出到文本文件。

这是我的代码:

import java.io.*;
import java.util.Scanner;

public class Lab4 {
    public static void main(String[] args) throws IOException {
        double distance;
        double velocity;
        double time;

        System.out.println("enter the velocity and time");
        Scanner sn = new Scanner(System.in);
        velocity = sn.nextDouble();
        time = sn.nextDouble();

        do {
            System.out.print(" Time cannot be smaller than zero and larger than ten");
            System.out.print("Please enter again");
            time = sn.nextDouble();
        } while(time < 0 && time > 10);

        System.out.print("please enter the file name");
        String filename = sn.nextLine();

        PrintWriter outputFile = new PrintWriter(filename);
        distance = velocity*time;
        outputFile.println(distance);
    }
}

问题1为什么我收到此错误:

PrintWriter outputFile = new PrintWriter(filename);
^
bad source file: .\PrintWriter.java
file does not contain class PrintWriter
Please remove or make sure it appears in the correct subdirectory of the sourcepath.

问题2:如何绘制该文件?

您的代码有很多问题,而aleb2000已经提到了一个大问题(请接受aleb2000的建议),但是我们只涉及您的问题最终涉及的问题,那就是您收到的错误。

之所以出现此错误,是因为提供的输出文件名实际上是Scanner 换行符,PrintWriter不知道该怎么做。 它不能识别为有效的路径和文件名。

为什么提供的文件名不正确? 好吧,这实际上很简单,在使用nextInt(),nextDouble()方法或任何希望提供数值的事件的Scanner方法时,Scanner类会有一些古怪之处,即当您点击在键盘上的Enter按钮上,您还提供了换行符,该换行符仍存储在Scanner缓冲区中,并且仅在使用Scanner.newLine()方法时(如您要求提供文件名时一样)才会释放。 换行符不会随您提供的数值一起发出,但是,当您提供文件名时,它将从缓冲区中拉出,并取代了实际为文件名键入的内容。 你能理解这个吗?

幸运的是,有一个解决此问题的简便方法,那就是在您上次输入数值后直接将Scanner.newLine()方法应用于任何内容(无变量),例如:

time = sn.nextDouble(); sn.nextLine();

您显然显然也希望在do / while循环中执行此操作,但我认为您应该取消do / while并仅使用while循环这样(您知道为什么吗?):

while(time < 0.0 || time > 10.0) {
    System.out.println("Time cannot be smaller than zero and larger than ten!");
    System.out.print("Please enter again: --> ");
    time = sn.nextDouble(); sn.nextLine();
} 

哦...而且不要在任务完成后同时关闭 PrintWriter对象和Scanner对象。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM