使用循环将文本文件打印到终端

时间:2015-10-25 22:01:39

标签: java while-loop

我可以打印出整个文本文件,但是我希望它能够打印学生姓名,所采取的测验总数以及分数的平均值。 这是输出:

输出:

Student Name         Number of Quizzes           Average
Kirk James Tiberius 95 86 87 92 95 93 91 94
Summers Buffy 76 57 98 92 91 83 85
Baker Tom 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100
Reynolds Malcolm 82 81 83 85 84 86 88 76 93
Bennet Elizabeth 91 93 95 94 89 93 95 96 94
Blutarsky John 0 0 0 0 0 0 0 0 0
Gale Dorthy 86 75 91 88 88 87 
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:907)
at java.util.Scanner.next(Scanner.java:1416)
at studenttester.StudentTester.main(StudentTester.java:36)
Java Result: 1

这是我的代码:

package studenttester;

public class Student {
    private String name;
    private double totalScore;
    private int numQuizzes;
    String grade;

    /**
     * Returns the name of a student
     *
     * @return the name of the student
     */
    public String getName() {
        return name;
    }

    /**
     * Adds a quiz score to the total quiz score of the student
     *
     * @param score the score of a quiz
     */
    void addQuiz(int score) {
        numQuizzes += 1;
        totalScore += score;
    }

    /**
     * Returns the total score of all the quizzes combined that student took
     *
     * @return the value of score
     */
    double getTotalScore() {
        return totalScore;
    }

    /**
     * Returns the average score of all the quizzes a student took
     *
     * @return
     */
    double getAverageScore() {
        return totalScore / numQuizzes;
    }
}

package studenttester;

import java.io.File;
import java.io.IOException;
import java.util.Scanner;

public class StudentTester {
    public static void main(String[] args) throws IOException {
        int digit = 0, amount = 0, quizzes = 0, sum = 0, next = 0;
        String name;
        boolean goodData = true;

        System.out.println("Student Name         Number of Quizzes           Average");

        Scanner reader = new Scanner(new File("quizScores.txt"));

        while (goodData) {
            name = reader.next();
            System.out.print(name);
            System.out.println(reader.nextLine());

            if (reader.hasNextInt()) {
                digit = reader.nextInt();
                sum = sum + digit;
                quizzes++;
            }
            sum = next;
            quizzes = next;
        }
        double quiz = 0;
        while (goodData) {
            name = reader.next();
            System.out.print(name);
            System.out.println(reader.nextLine());

            if (reader.hasNextInt()) {
                digit = reader.nextInt();
                sum = digit + sum;
                quizzes++;
                sum = next;
                quizzes = next;
            }
            System.out.println(name);
            System.out.println(sum / quizzes);
        }
    }
}

我认为我需要循环来识别整数和名称,但不确定如何这样做。

0 个答案:

没有答案