简体   繁体   English

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

[英]Program compiles but wont run when given filename

Working on this program that takes scores form a file and calculates averages, and then tells the averages from the user. 在这个程序上工作,它将得分形成一个文件并计算平均值,然后告诉用户的平均值。 Everything is done though I'm not sure why it wont accept my file scores.txt 尽管我不确定为什么它不会接受我的文件得分.txt,但一切都已完成

scores.txt (the file that contains the students scores) 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 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 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()));
        }
    }
}

I click compile, nothing. 我点击编译,没有。 Type scores. 输入分数。 Get a huge error. 得到一个巨大的错误。 Recompile. 重新编译。 Try scores.txt, still getting a huge error. 尝试得分.txt,仍然会收到很大的错误。

EDIT: I get this type of error 编辑:我得到这种类型的错误

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)

I click the tab in Eclipse that shows my StudentGradebookScores.java. 我单击Eclipse中显示StudentGradebookScores.java的选项卡。 I click the green play button that stands, I click in the Console and type scores or scores.txt 我单击绿色播放按钮,然后单击控制台并键入score或scores.txt

And your program as written will then promptly try to parse scores or scores.txt as a number. 然后,您编写的程序将立即尝试将分数或得分.txt解析为数字。 Either load your command line parameters (Eclipse will let you do this you know), or allow your program to accept a file name and use this to open a file from Scanner input -- your program does not do this at present. 加载命令行参数(Eclipse会让你知道),或允许你的程序接受文件名并使用它来打开扫描仪输入的文件 - 你的程序目前不这样做。

In other words, change this: 换句话说,改变这个:

   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()));
    }

to something like 喜欢的东西

   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);

       //.....
   }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM