我正在尝试编写一个程序,允许用户以整数形式输入一系列考试分数。
我希望输出看起来像这样:
输入一个整数,或 -99 退出:80
输入一个整数,或 -99 退出:95
输入一个整数,或 -99 退出:65
输入一个整数,或-99退出:-99
最大:95 最小:65
第二次运行:
输入一个整数,或-99退出:-99
您没有输入任何数字。
我记下了第一部分,但当我输入 -99 时,我似乎无法找到如何获得“您没有输入任何数字”行。
这就是我到目前为止所拥有的。
import java.util.Scanner; // Needed for the Scanner class
/**
This program shows the largest and smallest exam scores. The user
enters a series of exam scores, then -99 when finished.
UPDATED to show even number of points using if-statement
*/
public class Grades
{
public static void main(String[] args)
{
int score = 0; // Exam score
int min = 100; // Hold smallest score
int max = 0; // Hold largest score
// Create a Scanner object for keyboard input.
Scanner keyboard = new Scanner(System.in);
// Display general instructions.
System.out.println("Enter an integer, or -99 to quit: ");
System.out.println();
// Get the first exam score.
System.out.print("Enter an integer, or -99 to quit: ");
score = keyboard.nextInt();
// Input exam scores until -99 is entered.
while (score != -99)
{
// Add points to totalPoints.
if (score > max)
max = score;
if (score < min)
min = score;
// Get the next number of points.
System.out.print("Enter an integer, or -99 to quit: ");
score = keyboard.nextInt();
}
// Display the largest and smallest score.
System.out.println("Largest: " + max);
System.out.println("Smallest: " + min);
}
}
最佳答案
引入一个变量来计算输入的数字并在 while 循环中增加怎么样?
或者作为替代方案,您可以在 while 循环之后检查数字是否发生变化:
if(min > max) {
System.out.println("You did not enter any numbers.");
}
else {
System.out.println("Largest: " + max);
System.out.println("Smallest: " + min);
}
这是可行的,因为一开始您将 min
变量初始化为 100
,将 max
变量初始化为 0
如果没有输入数字,则 min > max
检查将得到 true
。
关于java - 我正在尝试编写一个程序,允许用户输入一系列考试分数作为整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40084686/