Java:阵列平均值计算器-读写文本文件

时间:2019-03-20 18:16:35

标签: java arrays

我的说明如下:“编写了一个Java程序,提示用户输入10个整数。该程序必须将10个整数保存到一个名为number.txt的文本文件中。该程序必须然后从文件中读回10个数字并显示这些数字的平均值提示:您应该将整数保存为字符串,然后从文件中读回它们后将它们转换回Integer。您的程序必须利用适当的异常处理以防写入或读取文件时出错。程序还需要包含正确的javadoc注释。” 更新:很抱歉,我没有赶时间,我在概念化写入和读取文件的外观时遇到了问题。我认为我的大多数代码是正确的。我只需要帮助调用读取文件来显示平均值,并帮助放置我对文件的写法

不好意思,我要整理一下我目前有的污点:

package average;

import java.io.*;
import java.nio.file.*;
import java.util.*;
import javax.swing.JOptionPane;


public class average {

    public static void main(String[] args) {

        Scanner kybd = new Scanner(System.in);  
        String prompt = JOptionPane.showInputDialog("Enter 10 numbers to average ");


        switch(prompt) {

        case "read": openFileRead(); readFromFile(); closeFileRead();
        break;
        case "write": openFileWrite(); writeToFile(); closeFile();
        break;
        default: System.out.println("Input not recognized.");


}

}
    public static void openFileRead() {      // gets file for "read"
        try {
            input = new Scanner(Paths.get("Numbers.txt"));
        }
        catch (IOException e) {
            System.out.println("Unable to read file");
        }
    }

    public static void openFileWrite() {     // gets file for "write"
        try {
            output = new Formatter("Numbers.txt");
        }
        catch (FileNotFoundException e) {
            System.out.println("Unable to open file");
        }

    }

    public static void readFromFile() {   
        System.out.print(average);

    }

      public static void writeToFile() {  
          Scanner input = new Scanner (System.in);
          int num[] = new int[10];
          int average = 0;
          int i = 0;
          int sum = 0;

          for (i=0;i<num.length;i++) {
              System.out.println("enter a number");
              num[i] = input.nextInt();
              sum=sum+num[i];
          }
          average=sum/10;
          System.out.println("Average="+average);
          }
    //required to close file for write
        public static void closeFile() {
            output.close();
        }

        //required to close file for read
        public static void closeFileRead() {
            input.close();
        }
} 

1 个答案:

答案 0 :(得分:0)

for (i=0; i<num.length; i++) 
{
   System.out.println("enter a number");
   num[i] = input.nextInt();
   sum += num[i];
}