在不使用数组的情况下找到给定整数的第二大数

时间:2019-10-20 21:40:03

标签: java drjava

使用if循环,我的任务是根据用户提供的数字将最大和第二大整数成对,最小和第二大整数成对。

我尝试了几种不同的if条件,虽然我的程序可以正确找到第二个最小整数,但是如果我应用相同的逻辑(反转大于/小于符号),我将无法得到正确的答案。

           numN = keyboard.nextInt();
           if (numN > numL1){
              numL1 = numN;
           }

           if (numN < numS1){
              numS1 = numN; 
           }
           else if (numN < numS2 && numS2 > numS1){
              numS2 = numN;
           }
           else if (numN > numL2 && numL2 < numL1){
              numL2 = numN;
           }

如果用户输入四个数字1,2,3,4

实际结果:最大和最小对:(4,4)(1,2)

所需结果:最大和最小对:(4,3)(1,2)

1 个答案:

答案 0 :(得分:0)

您可以按照以下步骤进行操作:

int max = Integer.MIN_VALUE, secondMax = Integer.MIN_VALUE, min = Integer.MAX_VALUE, secondMin = Integer.MAX_VALUE;

    int input = keyboard.nextInt();
    if (input > max) {
        secondMax = max;
        max = input;
    } else if (input > secondMax) {
        secondMax = input;
    }
    if (input < min) {
        secondMin = min;
        min = input;
    } else if (input < secondMin) {
        secondMin = input;
    }