[英]how to get min/max of user input?
打印最大值时,结果始终为 -1,绝不应在计算中使用 -1。 -1 应该只停止代码。 min 始终为 2147483647,这显然是不正确的。
public static void main(string [] args){
findMinMax(){
{do{System.out.print("Type a number (or -1 to stop): ");
num = console.nextInt();
}while(num != -1);{
}if (min < num) {
min = num;
}if (num > max) {
max = num;
}
System.out.println("maximum was : " + max);
System.out.println("minimum was : " + min);
}
}
}
例如,如果按顺序输入数字 5、2、17、-1,则结果应为
Type a number (or -1 to stop): 5
Type a number (or -1 to stop): 2
Type a number (or -1 to stop): 17
Type a number (or -1 to stop): 8
Type a number (or -1 to stop): -1
Maximum was 17
Minimum was 2
结果是目前
Type a number (or -1 to stop): 5
Type a number (or -1 to stop): 2
Type a number (or -1 to stop): 17
Type a number (or -1 to stop): 8
Type a number (or -1 to stop): -1
maximum was : -1
minimum was : 2147483647
我遇到了心理障碍,无法弄清楚。
您的代码块有一些问题。
检查以下代码并更正您的代码:
int num = 0;
Scanner console = new Scanner(System.in);
int min = Integer.MAX_VALUE;
int max = Integer.MIN_VALUE;
do {
System.out.println("Type a number (or -1 to stop): ");
num = console.nextInt();
if(num == -1)
break;
if (num < min){
min = num;
}
if(num > max){
max = num;
}
} while (true);
System.out.println("maximum was : " + max);
System.out.println("minimum was : " + min);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.