gpt4 book ai didi

java - 如何从用户那里读取 10 个整数,并在不使用数组的情况下识别第二大整数?

转载 作者:行者123 更新时间:2023-12-02 01:07:49 25 4
gpt4 key购买 nike

public static void main (String [] args) {

//declare variables

int numbers;
int secondHighest;

// create scanner to enter 10 digits

Scanner scanner = new Scanner(System.in);
System.out.print("Enter 10 digits: ");
numbers = scanner.nextInt();



for (numbers = 0; numbers > 10; numbers++);

for (secondHighest =+ 0 ; secondHighest < 10; secondHighest++)
System.out.print( secondHighest);

这就是我达到的程度,我可以让用户输入这 10 个数字,但是在弄清楚如何让程序识别这 10 个数字中哪一个是第二高的问题时遇到了问题,还值得一提的是,这些数字需要一行写成这样:

提供10个整数:67 -468 36 1345 -7778 0 34 7654 45 -666

第二大的是:1345

最佳答案

您可以按如下方式进行:

import java.util.Scanner;

public class Main {
public static void main(String[] args) {
int num = 0, highest = Integer.MIN_VALUE, secondHighest = Integer.MIN_VALUE + 1;
Scanner scanner = new Scanner(System.in);
for (int i = 1; i <= 10; i++) {
System.out.print("Enter an integer: ");
num = scanner.nextInt();
if (num > secondHighest && num <= highest) {
secondHighest = num;
}
if (num > highest) {
secondHighest = highest;
highest = num;
}
}
System.out.println("Second highest number is: " + secondHighest);
}
}

示例运行:

Enter an integer: 10
Enter an integer: -2
Enter an integer: 0
Enter an integer: 34
Enter an integer: -78
Enter an integer: 78
Enter an integer: 56
Enter an integer: 0
Enter an integer: 89
Enter an integer: -34
Second highest number is: 78
<小时/>

[更新]

如果您想在同一行中输入所有数字,请按以下步骤操作:

import java.util.Scanner;

public class Main {
public static void main(String[] args) {
int num = 0, highest = Integer.MIN_VALUE, secondHighest = Integer.MIN_VALUE + 1;
Scanner scanner = new Scanner(System.in);
System.out.print("Enter 10 integers: ");

for (int i = 1; i <= 10; i++) {
if (scanner.hasNextInt()) {
num = scanner.nextInt();
}
if (num > secondHighest && num <= highest) {
secondHighest = num;
}
if (num > highest) {
secondHighest = highest;
highest = num;
}
}
System.out.println("Second highest number is: " + secondHighest);
}
}

示例运行:

Enter 10 integers: 10 -3 24 0 56 -5 34 78 89 -6
Second highest number is: 78

关于java - 如何从用户那里读取 10 个整数,并在不使用数组的情况下识别第二大整数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59794957/

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