比较do-while循环中的字符串

时间:2015-10-07 20:52:11

标签: java loops

我遇到以下代码问题。它应该向用户询问有关学生的一系列问题'测试分数并返回平均测试分数,这部分工作正常。

我的问题是我应该使用" while-loop"它将运行程序,然后询问用户是否希望程序结束。如果他们回应'#34;不,"然后它应该重新启动并要求一组新的测试分数等。

当我尝试执行程序时,它可以正常运行,直到它应该重新启动的部分。打印出平均值后,它会问我是否要关闭程序,但它不允许我输入任何内容。就像程序结束它自己一样。< / p>

我围绕while循环做了一些评论,解释了我的逻辑,因为我怀疑问题会在哪里。

import java.util.Scanner;
import java.text.DecimalFormat;
import java.text.NumberFormat;
public class testScores {
    public static void main(String[] args)  {
        NumberFormat formatter = new DecimalFormat("####.##");
        Scanner keys = new Scanner(System.in);
// Initialize endProgram to "no"
        String endProgram = "no";
// Declare there's going to be a string called end
        String end;
        double totalScore = 0;
        double averageScore = 0;
        do  {
// Do all of this now before you check anything
            int number = getNumber(keys);
            totalScore = getScores(number, keys, totalScore);
            averageScore = getAverage(totalScore, number, averageScore);
            printAverage(averageScore, formatter);
            System.out.println("Do you want to end the program?");
            end = keys.nextLine();
// Now check if end and endProgram contain the same string
        }  while (end.equals(endProgram));
// Apparently not
    }
        public static int getNumber(Scanner keys)  {
        System.out.println("How many students took the test?");
        int number = keys.nextInt();
        return number;
    }
    public static double getScores(int number, Scanner keys, double totalScore)  {
        for(int counter = 1; counter <= number; counter++)  {
            System.out.println("Enter their score.");
            double score = keys.nextDouble();
            totalScore = totalScore + score;
        }
        return totalScore;
    }
    public static double getAverage(double totalScore, int number, double averageScore)  {
        averageScore = totalScore / number;
        return averageScore;
    }
    public static void printAverage(double averageScore, NumberFormat formatter)  {
        System.out.println("The average is " + formatter.format(averageScore));
    }
}

我尝试了一些不同的事情,例如使用一段时间而不是一段时间,然后切换出来&#34;结束&#34; for&#34; endProgram&#34;检查&#34; endProgram&#34;重置它的价值后,一切都没有成功。如果有人能帮助我,我将不胜感激。

1 个答案:

答案 0 :(得分:-1)

你应该沿着这条路尝试一下。要点是 - do-while在这里是错误的,因为它检查不存在的字符串:

    String end = "";
  /* rest of variables */

       while (!(end.equals(endProgram) )) {
// Do all of this now before you check anything
            int number = getNumber(keys);
            totalScore = getScores(number, keys, totalScore);
            averageScore = getAverage(totalScore, number, averageScore);
            printAverage(averageScore, formatter);
            System.out.println("Do you want to end the program?");
            end = keys.nextLine();
// Now check if end and endProgram contain the same string
        }