【问题标题】:Finding the second largest number of given integers without using array在不使用数组的情况下查找给定整数的第二大数量
【发布时间】:2019-10-20 21:40:03
【问题描述】:

使用 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)

【问题讨论】:

  • 没有数组?制造漏洞。 java.util.List l = new java.util.ArrayList/Vector/Stack/LinkedList&lt;?&gt;()另外,为什么一开始就禁止你使用数组?
  • 教授的规矩,不知道为什么不允许

标签: java drjava


【解决方案1】:

你可以这样做:

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

【讨论】:

    猜你喜欢
    • 2019-05-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-10
    • 1970-01-01
    • 2017-07-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多