gpt4 book ai didi

java - 在不使用数组的情况下查找列表中的两个最大数字

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:20:16 24 4
gpt4 key购买 nike

我被作业困住了。基本上,我们需要创建一个程序来查找用户输入的列表中的最大和最小整数。并在用户输入 0 时停止。但是我们不允许使用数组来解决这个问题。

还有一个条件:如果最大值出现不止一次,则该值应同时列为最大值和第二大值,如以下示例运行所示。

我满足了程序的第一个条件,但是我无法满足第二个条件。

import java.util.Scanner;
public class FindTwoLargest {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
int num = 1, max1st = 0, max2nd = 0;
int count = 1;
System.out.println("This program allows the user to create a list integers until the user enters 0");
System.out.println("The program will print the Largest value and the Second largest value from the list!");
while(num != 0) {
System.out.print("Integer No." + count + " ");
num = sc.nextInt();

if(num >= max1st && num >= max2nd) {
max1st = num;
}
if(num >= max2nd && num < max1st) {
max2nd = num;
}
count++;
}
System.out.println("The largest value is " + max1st);
System.out.println("The second largest value is " + max2nd);

}
}

我试过使用这个代码。

 if(num >= max2nd && num <= max1st) {
max2nd = num;
}

但是当我运行程序时 https://imgur.com/a/YMxj9qm - 这表明。

它应该打印 75 和 45 。怎么做才能满足第一个条件和第二个条件?

最佳答案

如果您超过最大数量 (max1st),您的新最大数量将设置为 num。但是你的第二大数字将是当前的最大数字。所以试试这个条件:

if (num > max1st) {
max2nd = max1st;
max1st = num;
} else if (num > max2nd) {
max2nd = num;
}

关于java - 在不使用数组的情况下查找列表中的两个最大数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57557747/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com