程序编译但在给定文件名时不会运行

时间:2015-03-04 23:23:09

标签: java

使用此程序将得分形成一个文件并计算平均值,然后告诉用户的平均值。虽然我不确定为什么它不接受我的文件得分.txt

,但一切都已完成

scores.txt(包含学生分数的文件)

5
6
95.2 89.1 98.0 78.9 100 67
100 99.6 100 100 90.1 82.2
100 85.5 85.1 74 81 79.4
98.6 71.5 68.9 62.4 56.9 0
100 100 100 88.3 91.6 81.3

StudentGradebookScores.java

import java.io.*;
import java.text.DecimalFormat;
import java.util.*;

public class StudentGradebookScores {
    public static void main(String[] args) throws IOException {
        DecimalFormat FMT = new DecimalFormat("#.#");

        try (Scanner input = args.length > 0 ? new Scanner(new File(args[0]))
                : new Scanner(System.in)) {
            GradeBook book = new GradeBook(input);
            System.out.println(book);
            System.out.printf("Overall Average: %s\n",
                    FMT.format(book.average()));
        }
    }
}

GradeBook.java

import java.io.*; 
import java.text.*;
import java.util.*;
import java.util.stream.*;

public class GradeBook {
    private List<double[]> students;
    private static final DecimalFormat FMT = new DecimalFormat("#.#");

    public GradeBook(Scanner input) {
        this.students = new ArrayList<double[]>();
        while (input.hasNextLine()) {
            double[] student = Arrays.stream(input.nextLine().trim().split("\\s+"))
                  .mapToDouble(Double::parseDouble)
                  .toArray();
            students.add(student);
        }
    }

    public double getScore(int student, int assignment) {
        return this.students.get(student)[assignment];
    }

    public double averageForStudent(int student) {
        return Arrays.stream(this.students.get(student))
                     .average()
                     .getAsDouble();
    }

    public double averageForAssignment(int assignment) {
        return this.students.stream()
                   .mapToDouble((assignments) -> assignments[assignment])
                   .average()
                   .getAsDouble();
    }

    public double average() {
        return IntStream.range(0, this.students.size())
                        .mapToDouble((s) -> this.averageForStudent(s))
                        .average()
                        .getAsDouble();
    }

    public String toString() {
        StringBuilder out = new StringBuilder();
        int numAssignments = this.students.stream()
                                 .mapToInt((assignments) -> assignments.length)
                                 .max()
                                 .getAsInt();

        // Header
        out.append("\t\t\t\tAssignment #:\n\t\t");
        for (int a = 0; a < numAssignments; a++) {
           out.append(a + 1).append('\t'); 
        }
        out.append("Avg\n");

        // Body
        for (int s = 0; s < this.students.size(); s++) {
            out.append("Student #").append(s + 1).append(":\t");
            for (int a = 0; a < numAssignments; a++) {
                out.append(FMT.format(this.getScore(s, a))).append('\t');
            }
            out.append(FMT.format(this.averageForStudent(s))).append('\n');
        }

        // Footer
        out.append("Average\t\t");
        for (int a = 0; a < numAssignments; a++) {
            out.append(FMT.format(this.averageForAssignment(a))).append('\t');
        }
        out.append('\n');

        return out.toString();
    }

    public static void main(String[] args) throws IOException {
        try (Scanner input = args.length > 0 ? new Scanner(new File(args[0])) :
                                               new Scanner(System.in)) {
            GradeBook book = new GradeBook(input);
            System.out.println(book);
            System.out.printf("Overall Average: %s\n",
                              FMT.format(book.average()));
        }
    }
}

我点击编译,没有。输入分数。得到一个巨大的错误。重新编译。尝试得分.txt,仍然会收到很大的错误。

编辑: 我得到了这种类型的错误

Exception in thread "main" java.lang.NumberFormatException: For input string: "scores"
    at sun.misc.FloatingDecimal.readJavaFormatString(Unknown Source)
    at sun.misc.FloatingDecimal.parseDouble(Unknown Source)
    at java.lang.Double.parseDouble(Unknown Source)
    at GradeBook$$Lambda$1/523429237.applyAsDouble(Unknown Source)
    at java.util.stream.ReferencePipeline$6$1.accept(Unknown Source)
    at java.util.Spliterators$ArraySpliterator.forEachRemaining(Unknown Source)
    at java.util.stream.AbstractPipeline.copyInto(Unknown Source)
    at java.util.stream.AbstractPipeline.wrapAndCopyInto(Unknown Source)
    at java.util.stream.AbstractPipeline.evaluate(Unknown Source)
    at java.util.stream.AbstractPipeline.evaluateToArrayNode(Unknown Source)
    at java.util.stream.DoublePipeline.toArray(Unknown Source)
    at GradeBook.<init>(GradeBook.java:21)
    at StudentGradebookScores.main(StudentGradebookScores.java:16)

1 个答案:

答案 0 :(得分:0)

  

我单击Eclipse中显示StudentGradebookScores.java的选项卡。我单击绿色播放按钮,我在控制台中单击并键入score或scores.txt

然后您编写的程序将立即尝试将分数或得分.txt解析为数字。加载命令行参数(Eclipse会让你知道),或允许程序接受文件名并使用它来打开扫描仪输入的文件 - 你的程序不做目前这个。

换句话说,改变这个:

   try (Scanner input = args.length > 0 ? new Scanner(new File(args[0]))
            : new Scanner(System.in)) {
        GradeBook book = new GradeBook(input);
        System.out.println(book);
        System.out.printf("Overall Average: %s\n",
                FMT.format(book.average()));
    }

类似

   if (args.length == 0) { 
       Scanner tempScanner = new Scanner(System.in);
       System.out.print("Enter file name: ");
       String fileName = tempScanner.nextLine();
       File file = new File(fileName);
       tempScanner.close();
       Scanner input = new Scanner(file);

       //.....
   }