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!");
}
所以,我试图输出最大数量,第二大数量和最小数量。我能够获得最小和最大,但不知道从哪里开始获得第二大。我认为这会起作用,但输出同样大的东西。我目前不想使用数组,因为这是家庭作业。请不要告诉我确切的答案,但是一些帮助和提示会很精彩!
答案 0 :(得分:3)
初始化像
这样的变量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;
}
答案 1 :(得分:0)
这是我使用来自Math类的静态方法max和min的解决方案:
newbutton
答案 2 :(得分:0)
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
int max = 0;
int smax = 0;
int num = 0;
while (num != -1) {
System.out.println("Enter number Or -1 to Stop:");
num = in.nextInt();
if (num >= max) {
smax = max;
max = num;
}
}
System.out.println("second max :"+smax);
}