如何让程序跟踪java中的min和max

时间:2015-10-02 13:30:16

标签: java max min

此程序需要输出最小答案数,并回答最大数。似乎无法让这一点正确。最后,结果还需要包括读取"输入的最小数字为"和"输入的最大数字是"

{
    public static void main(String[] args)
 {
    // display operational messages
    System.out.println("Please enter test scores that range from 0  to        100.");
    System.out.println("To end the program enter 999.");
    System.out.println();  // print a blank line

    // initialize variables and create a Scanner object
    double scoreTotal = 0;
    int scoreCount = 0;
    int testScore = 0;
    Scanner sc = new Scanner(System.in);

    //declaring what is min and what is max
    int x = 100;
    int y= 0; 
    int max = Math.max(x, y); // max is 100
    int min = Math.min(x, y); // min is 0

    // get a series of test scores from the user
    while (testScore != 999)
   '   enter code here`    {
        // get the input from the user
        System.out.print("Enter score: ");
        testScore = sc.nextInt();

        // accumulate score count and score total
        if (testScore <= 100)
        {
            scoreCount = scoreCount += 1;
            scoreTotal = scoreTotal += testScore;
        }
        else if (testScore != 999)
            System.out.println("Invalid entry, not counted");



    }

    // display the score count, score total, and average score
    double averageScore = scoreTotal / scoreCount;
    String message = "\n" +
                     "Score count:   " + scoreCount + "\n"
  `enter code here`                 + "Score total:   " + scoreTotal  +            "\n"
                   + "Average score: " + averageScore + "\n";
    System.out.println(message);

}

2 个答案:

答案 0 :(得分:1)

对于:最后,结果还需要包括读取&#34;输入的最小数字为&#34;和&#34;输入的最大数字是&#34;

我建议将您的分数或输入的数字存储在列表(Arraylist)或任何其他集合中 然后使用java.util.Collections max min 方法。

List<Integer>list=new ArrayList<Integer>();
Collections.max(list);
Collections.min(list);

答案 1 :(得分:0)

一个简单的解决方案是在两个单独的整数中跟踪最小和最大分数,并在您查看测试结果时对其进行修改。如果插入的测试分数大于我们当前的最大值,则我们更新最大值以匹配分数。如果它低于我们目前的最低值,那么我们会更新最小值:

...
int minScore = 100, maxScore = 0;
while (testScore != 999)
   '   enter code here`    {
        // get the input from the user
        System.out.print("Enter score: ");
        testScore = sc.nextInt();

        // accumulate score count and score total
        if (testScore <= 100)
        {
            scoreCount = scoreCount += 1;
            scoreTotal = scoreTotal += testScore;
            maxScore = Math.max(maxScore, testScore);
            minScore = Math.min(minScore, testScore);
        }
        ...