这是我的代码:

public static void main(String[] args) throws IOException {
        writeToFile ("c:\\scores.txt");
        processFile("c:\\scores.txt");
    }
    public static void writeToFile (String filename) throws IOException {
        BufferedWriter outputWriter = new BufferedWriter(new FileWriter(filename));
        Scanner reader = new Scanner (System.in);
        int Num;
        System.out.println ("Please enter 7 scores");
            for (int i = 0; i < 7; i++) {

                Num= reader.nextInt ();

                outputWriter.write(Num);

                if(i!=6) {
                    outputWriter.newLine();
                }
            }

        outputWriter.flush();
        outputWriter.close();
}

    public static void processFile (String filename) throws IOException, FileNotFoundException
    {
        double sum=0.00;
        double number;
        double average;
                int count = 0;
        BufferedReader inputReader = new BufferedReader (new InputStreamReader(new FileInputStream(filename)));
        String line;

        while((line = inputReader.readLine()) != null)
        {
            number= Double.parseDouble(line);
                        System.out.println(number);
                        count ++;
            sum += (number);
            System.out.print ("Total Sum:  ");
            System.out.println(sum);
            System.out.print("Average of Scores:  ");
            average=sum/count;
            System.out.println(average);
        }
        inputReader.close();
    }


这就是我的输出。

Please enter 7 scores
2
3
5
6
8
9
1
Exception in thread "main" java.lang.NumberFormatException: empty String
    at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:1011)
    at java.lang.Double.parseDouble(Double.java:540)
    at writefile.Writefile.processFile(Writefile.java:52)
    at writefile.Writefile.main(Writefile.java:19)
Java Result: 1


我不知道该如何解决。我不确定如何解决浮点十进制或空字符串错误。文件中有奇怪的符号,没有整数。我该如何解决?请具体说明,因为我只是Java的初学者。

最佳答案

outputWriter.write(1);并不代表outputWriter.write("1");
您需要将outputWriter.write(Num);更改为outputWriter.write(""+Num);
请参考outputstream.write(int)

10-01 09:41
查看更多