如何使用Scanner和for循环(无阵列)找到第二大数字

时间:2009-12-29 16:59:01

标签: java algorithm java.util.scanner

因此,我可以轻松完成任务以找到最大数量,然后如果可以除以3,则打印出来。但不知道如何从用户序列中找到第二大数字。 谢谢你的任何提示!

public class SecondLargest {

    public static void main(String[] args) {
        int max = 0;
        Scanner scan = new Scanner(System.in);
        System.out.println("How many numbers?");
        int n = scan.nextInt();

        System.out.println ("Write numbers: ");
        for(int i=0; i<n; i++){
            int c = scan.nextInt();
            if(c>=max && c%3 == 0){
                max = c;
                }
            else
                System.out.println("There is no such number.");



        }
        System.out.println(max);
    }
}

3 个答案:

答案 0 :(得分:2)

int secondLargest = 0;
.....
for (..) {
   ....
   if (c % 3 == 0) {
       if (c >= max) {
           secondLargest = max;
           max = c;
       }
       if (c >= secondLargest && c < max) {
           secondLargest = c;
       }
   }
   ....
}

答案 1 :(得分:2)

你只需要保留2个变量,一个用于最大值,另一个用于second_maximum,并适当地更新它们。

有关更一般的方法,请查看selection algorithms

答案 2 :(得分:0)

Below code will work

import java.util.Scanner;

public class Practical4 {
    public static void main(String a[]) {
        int max = 0, second_max = 0, temp, numbers;
        Scanner scanner = new Scanner(System.in);
        System.out.println("How many numbers do you want to enter?");
        numbers = scanner.nextInt();
        System.out.println("Enter numbers:");
        for (int i = 0; i < numbers; i++) {
            if (i == 0) {
                max = scanner.nextInt();
            } else {
                temp = scanner.nextInt();
                if (temp > max) {
                    second_max = max;
                    max = temp;
                }
                else if(temp>second_max)
                {
                 second_max=temp;
                }
            }
        }
        scanner.close();
        System.out.println("Second max number is :" + second_max);
    }
}