簡體   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