gpt4 book ai didi

java程序要求用户输入第二大和最大的数字

转载 作者:行者123 更新时间:2023-12-02 04:41:31 25 4
gpt4 key购买 nike

//java program that asks user to input a number and print the 1st and 2nd largest numbers

import java.util.Scanner;

public class twolargestnum
{
public static void main(String args[])
{
Scanner input=new Scanner(System.in);

int largest_2=0; //initializes second number
int largest=0; //initializes first number
int number;
int counter=0;//initializes counter



while(counter<10)
{
System.out.println("enter the number:");
number=input.nextInt();//prompts user

if(largest<number){
largest=number;//stores number to largest
largest_2=largest;}//stores largest to second largest or largest_2
else{

if(largest_2<number &&largest>largest_2)
largest_2=number; //stores second largest to number


}
counter=counter+1;//counts number input 10 times
}

System.out.println("The first largest number is " +largest);//displays largest number inputed
System.out.println("The second largest number is " +largest_2);//displays second largest number inputed

}

}

输出

enter the number:
99
enter the number:
88
enter the number:
77
enter the number:
66
enter the number:
55
enter the number:
44
enter the number:
33
enter the number:
22
enter the number:
11
enter the number:
10
The first largest number is 99
The second largest number is 99

如您所见,程序将第二大数字显示为 99,而不是 88。我做错了什么?

最佳答案

至少交换这两行:

        largest=number;//stores number to largest
largest_2=largest;//stores largest to second largest or

关于java程序要求用户输入第二大和最大的数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30129868/

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