public static void main(String[] args) {
int num;
int large;
int small;
int secondLarge;
Scanner scan = new Scanner(System.in);
System.out.print("Input a number: ");
num = scan.nextInt();
large = num;
small = num;
secondLarge = num;
for (int x = 9; x > 0; x--) {
System.out.print("Enter " + x + " more number: ");
num = scan.nextInt();
if (num > large) {
large = num;
}
if (num > secondLarge) {
secondLarge = num;
}
if (secondLarge > large) {
large = secondLarge;
}
if (num < small) {
small = num;
}
} System.out.println( large + " is the largest number, " + secondLarge + " is the second largest number and " + small + " is the smallest number!");
}
因此,我试图输出最大,第二大和最小的数字。我能够得到最小和最大的东西,但是不知道从哪里开始获得第二大的东西。我以为这会工作,但它输出的东西一样大。我目前不打算使用数组,因为这是家庭作业。请不要告诉我确切的答案,但是一些帮助和提示会很棒!
最佳答案
初始化变量如
int largest=0;
int secondlargest=0;
int smallest=Integer.MAX_VALUE;
条件应该像
if(number>=largest){
secondlargest=largest;
largest=number;
}else if(number>secondlargest){
secondlargest=number;
}
if(number<smallest){
smallest=number;
}