修改脚到米程序读取,写入文件。名为“feet.txt”的输入文件和输出文件“meters.txt”

时间:2018-03-09 19:41:35

标签: java

我们被要求修改从第2周开始读取的脚到米程序,然后写入文件。输入文件应命名为“feet.txt”,输出文件名为“meters.txt”。

输入文件应仅包含双精度值。输出文件应在每行上有脚和米,格式化为单个小数。输出文件中一行的示例:(假设从文件中读取了5.2) 5.2英尺隐蔽到1.6米。我在控制台中收到以下错误:

Exception in thread "main" java.io.
FileNotFoundException: input.txt (No such file or directory)
    at java.base/java.io.FileInputStream.open0(Native Method)
    at java.base/java.io.FileInputStream.open(FileInputStream.java:196)
    at java.base/java.io.FileInputStream.<init>(FileInputStream.java:139)
    at java.base/java.io.FileReader.<init>(FileReader.java:72)
    at lab8p2.main(lab8p2.java:21)

代码:

import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.*;

public class feet_to_meters {

    public static void main(String[] args) throws FileNotFoundException {
        double feet, meters; 
        Scanner fileScanner = new Scanner(new File("feet.txt"));
        PrintWriter out = new PrintWriter("meters.txt");
        while(fileScanner.hasNextDouble()) {
            // read feet
            feet = fileScanner.nextDouble();
            // calculate meters: feet * 0.305
            meters = feet * 0.305;
            //write meters
            out.write(Double.toString(meters));
        }
        fileScanner.close();
        out.close();
        System.out.println("Output successfully written in file");
    }
}

0 个答案:

没有答案