我需要创建一个程序,提示用户输入一个整数然后打印到目前为止输入的最高值(例如“输入一个数字:5到目前为止最高的数字:5,输入一个数字:6,到目前为止最高的数字:6)然后当用户输入一个负数时退出。我已经打印了问题,但我的循环一直在运行
发布于 2018-10-23 09:12:34
仅在不显示任何代码的情况下提出问题并不好。你必须展示你的尝试,我们可以改进它。如果你这样问,也许这是你的功课,给出完整答案是不好的。但是,您可以轻松地检查它并输入数字,直到它为正。我给出了这个答案:
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int num = in.nextInt();
int max = Integer.MIN_VALUE; // I use this but it will replaced with first number
while (num >= 0) {
if (num > max)
max = num;
num = in.nextInt();
}
System.out.println("max: " + (max == Integer.MIN_VALUE ? "There is no input entered" : max));
}
但是,如果您执行其他操作,请将其发布以进行改进。
发布于 2018-10-23 10:04:44
因为你的标题是“Java程序”,所以你可以写这样的东西,
public static void main(String[] args) throws Exception {
Scanner sc = new Scanner(System.in);
int max = 0;
System.out.println("Please enter a number and any negative number or non number to end the program.");
while (sc.hasNextInt()) {
int num = sc.nextInt();
if (num < 0) {
break;
} else {
if (max < num) {
max = num;
}
}
System.out.println("So far maximum number: " + max);
}
sc.close();
System.out.println("Program ends");
}
该程序将继续采用整数输入并打印到目前为止遇到的最大值,并且在取任何负数时,程序将结束。
https://stackoverflow.com/questions/-100002963
复制相似问题