Skip to content
Advertisement

How to find second largest number using Scanner and for loop(no array)

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

Advertisement

Answer

int secondLargest = 0;
.....
for (..) {
   ....
   if (c % 3 == 0) {
       if (c >= max) {
           secondLargest = max;
           max = c;
       }
       if (c >= secondLargest && c < max) {
           secondLargest = c;
       }
   }
   ....
}
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement