-1

所以我可以很容易地完成任务找到最大的数字,然后如果可以被三除,打印出来。但不知道如何从用户序列中找到第二大数字。感谢您的任何提示!

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);
    }
}
4

3 回答 3

2
int secondLargest = 0;
.....
for (..) {
   ....
   if (c % 3 == 0) {
       if (c >= max) {
           secondLargest = max;
           max = c;
       }
       if (c >= secondLargest && c < max) {
           secondLargest = c;
       }
   }
   ....
}
于 2009-12-29T17:03:34.237 回答
2

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

对于更通用的方法,请查看选择算法

于 2009-12-29T17:03:58.640 回答
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);
    }
}
于 2017-06-15T06:10:11.317 回答