我有一个问题,要求我输入一些考试成绩,以找到最高分和最低分。 (突出问题。)
float sum = 0, score1, score2 = 0, score3 = 0;
do
{
System.out.println("Enter a score [negative score to quit]: ");
Scanner Score1 = new Scanner(System.in);
score1 = Score1.nextFloat();
if (score1>score2)
{
max = score1;
min = score2;
}
else if(score1<score2)
{
max = score2;
min = score1;
}
else{
score3 = score2;
}
}
}
while (score1>=0);
System.out.printf("Minimun Score = %.0f\n", min);
System.out.printf("Maximum Score = %.0f\n", max);
Enter a score [negative score to quit]:
99
Enter a score [negative score to quit]:
1
Enter a score [negative score to quit]:
6
Enter a score [negative score to quit]:
5
Enter a score [negative score to quit]:
-1
Minimum Score = 5
Maximum Score = 6
BUILD SUCCESSFUL (total time: 7 seconds)
问题是它只比较我输入的最新2分。 我该如何解决这个问题?
答案 0 :(得分:0)
if-else
阶梯中的逻辑不正确。
您可能会发现以下内容:
class Test
{
public static void main (String[] args) throws java.lang.Exception
{
try(Scanner Score1 = new Scanner(System.in))
{
//Marks are in range of 0-100
float curNum, max = -1, min = 101, sum = 0, sumsq = 0;
boolean flg = true;
while(flg)
{
System.out.println("Enter a score [negative score to quit]: ");
curNum = Score1.nextFloat();
if(curNum<0) break;
if(max < curNum) max = curNum;
if(min > curNum) min = curNum;
sum += curNum;
sumsq += (curNum*curNum);
}
System.out.printf("Minimun Score = %.0f\n", min);
System.out.printf("Maximum Score = %.0f\n", max);
}
}
}
您可以找到它here
答案 1 :(得分:0)
do-while逻辑可能无法在上面的代码中使用。请参阅下面的工作代码..
float sum = 0, score = 0;
float min = 0, max = 0, ave = 0;
Scanner stdInput = new Scanner(System.in);
System.out.println("Enter the scores: ");
min = max = score = stdInput.nextFloat();
do {
System.out.println("Enter a score [negative score to quit]: ");
if (score > max) {
max = score;
}else if (score < min) {
min = score;
}
sum += score;
// Read the input here so that, the code does not process the negative input.
score = stdInput.nextFloat();
} while (score >= 0);
System.out.println(min);
System.out.println(max);