有没有办法将数组的所有值打印到输出文件?

时间:2019-04-17 17:50:37

标签: java arrays eclipse file-io

我制作了一个 RainFall 类,该类存储全年的降雨量(以英寸为单位)(总共12个值)。我可以使用它,但是现在我需要将这些值打印到outputFile(我称为 RainFall.txt )。当我运行代码并检查文件时,它仅存储数组的第一个值。

我已经尝试使用try and catch方法,但是它不会显示任何内容。

import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.text.DecimalFormat; 

public class RainFallMain {
    public static void main(String[] args) throws FileNotFoundException {

        // Array representing rainfall figures
        // position correlates to the month
        double[] thisYear = { 1.6, 2.1, 1.7, 3.5, 2.6, 3.7, 3.9, 2.6, 2.9, 4.3, 2.4, 3.7 };
        RainfallClass r = new RainfallClass(thisYear);
        PrintWriter outputFile = new PrintWriter("RainFall.txt"); 
               for (int i = 0; i < thisYear.length; i++)
               {
                   outputFile.println(thisYear[i]);
                   outputFile.close();
               }

输出文件应列出所有12个值。

1 个答案:

答案 0 :(得分:0)

仅在完成所有写入后,才应关闭输出文件。

 public static void main(String[] args) throws FileNotFoundException {
    // Some statements
    for (int i = 0; i < thisYear.length; i++){
        outputFile.println(thisYear[i]);    
    }
    outputFile.close(); // Moved out of the for loop
    // Some more statements if there. 
}