我想知道是否有人可以看看我的代碼,看看我做錯了什麼。我試圖讓我的程序寫入一個文件,但它不會。我需要一些幫助才能將結果寫入文件。是的,我知道很多問題已經被問及這個問題,是的,我看着他們,有不少。我只是不能真正使用它對我沒有意義的例子。任何幫助都會很棒。java寫入文件不起作用
import java.util.Scanner;
import java.io.*;
public class DistanceFile {
public static void main(String[] args) throws IOException {
int time; //hours traveled
int hour;//for the formula
String FileName;
Scanner scanner= new Scanner(System.in);
System.out.println("Enter the speed of the vehicle");
int speed= scanner.nextInt();
while (speed<=0){
System.out.println("Please enter a valid speed");
speed=scanner.nextInt();
}
System.out.println("Enter the number of hours traveled");
time=scanner.nextInt();
while (time<=0){
System.out.println("Please enter a valid time");
time=scanner.nextInt();
}
hour=0;
PrintWriter outputFile= new PrintWriter("DistanceFile.txt");
for( hour = 1; hour <= time; hour++)
System.out.println(hour+ " " + (hour * speed));
outputFile.print(speed+"");
outputFile.print(time+" ");
outputFile.close();
outputFile.flush()在關閉之前 – Erik
'close()'方法應該進行刷新。什麼是錯誤?該文件根本沒有被創建,或者被創建並且不包含預期的輸出? – PNS
該代碼似乎爲我工作(DistanceFile.txt在工作目錄中創建) –