While语句中整数的最小值和最大值

时间:2017-10-24 05:46:02

标签: java

我是Java的初学者,通过课程学习,但是当尝试做一个有时可以输入0到100之间的数字的语句时,直到他们键入999,然后它给出了输入的数字的数量,最高号码,最低号码和所有号码的平均值。

我目前的代码导致999第一次没有注册,最高和最低的数字都是多位数字,数字的数量包括超出限制的任何数字和999,以及平均值。

这就是我所拥有的:

import java.util.Scanner;

public class TestScoreStatistics {

    public static void main(String[] args) {
        int numberOfScores = 0;
        int highest;
        int lowest;
        double average;
        Integer score = 0;
        int sumOfScores = 0;
        Scanner input = new Scanner(System.in);

        System.out.println("Please enter a grade or enter 999 to finish >> ");
        score = input.nextInt();
        sumOfScores = sumOfScores + score;

        while (score < 100 || score > 0) {
            ++numberOfScores;
            System.out.println("Please enter a grade or enter 999 to finish >> ");
            score = input.nextInt();
            sumOfScores = sumOfScores + score;
            ++numberOfScores;

            while (score > 100 || score < 0) {
                System.out.println("You entered an invalid score. Please enter a valid test score.");
                System.out.println("Please enter a grade or enter 999 to finish >> ");
                score = input.nextInt();
                sumOfScores = sumOfScores + score;

                if (score == 999) {
                    highest = score.MIN_VALUE;
                    lowest = score.MAX_VALUE;
                    average = sumOfScores / numberOfScores;
                    System.out.println("Number of Scores you entered: " + numberOfScores);
                    System.out.println("Highest Score: " + highest);
                    System.out.println("Lowest Score: " + lowest);
                    System.out.println("Average Score: " + average);
                }
            }
        }
    }
}

感谢。

2 个答案:

答案 0 :(得分:1)

考虑这一行

while(score < 100 || score > 0)

如果得分为999,您认为它是否包括在内?

如果您使用简单的调试,您会立即发现

答案 1 :(得分:0)

while (score < 100 && score > 0) {
 ++numberOfScores;
 System.out.println("Please enter a grade or enter 999 to finish>> ");
 score = input.nextInt();
 sumOfScores = sumOfScores + score;
 ++numberOfScores;
 highest=Integer.MIN_VALUE;
 lowest=Integer.MAX_VALUE;
 if(score>highest)
 highest=score;// this will find the highest , as user is entering 
 else if(score<lowest)
 lowest=score;  // this will find the highest , as user is entering

if (score == 999) {
  average = sumOfScores / numberOfScores;
  System.out.println("Number of Scores you entered: " + numberOfScores);
  System.out.println("Highest Score: " + highest);
  System.out.println("Lowest Score: " + lowest);
  System.out.println("Average Score: " + average);
 }
}