首页 > 解决方案 > 如何获得最小/最大用户输入?

问题描述

打印最大值时,结果始终为 -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

我遇到了心理障碍,无法弄清楚。

标签: java

解决方案


您的代码块有一些问题。

  1. 您对 min, max 的条件检查不正确。
  2. 另外,您必须将 min,max 检查块放在循环内

检查以下代码并更正您的代码:

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);

推荐阅读