views:

607

answers:

2

Hi.So I can easily accomplish task to find largest number and then if can be divided by three, print out. But do not know how to find second largest number from users sequence. Thanks for any hints!

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);
    }
}
+2  A: 
int secondLargest = 0;
.....
for (..) {
   ....
   if (c % 3 == 0) {
       if (c >= max) {
           secondLargest = max;
           max = c;
       }
       if (c >= secondLargest && c < max) {
           secondLargest = c;
       }
   }
   ....
}
Bozho
Thanks. Its not homework. I'm just training random stuff to be more fluent.
landscape
When you update max, you'll also want to update secondLargest.
Andrew Coleson
good point. updated.
Bozho
+2  A: 

You just need to keep 2 variables, one for maximum and another for second_maximum and update them appropriately.

For a more general approach, take a look at selection algorithms

Drakosha