Find Two largest numbers in a list without using Array

Joshua Salcedo :

I'm Stuck with my homework. Basically,we need to Create a program to find the largest and smallest integers in a list entered by the user.And stops when the user enters 0. However we are not allowed to user arrays for this problem.

and one more condition : If the largest value appears more than once, that value should be listed as both the largest and second-largest value, as shown in the following sample run.

I have met the first condition of the program however I cannot meet the 2nd condition.

import java.util.Scanner;
public class FindTwoLargest {
    public static void main(String args[]) {
        Scanner sc = new Scanner(System.in);
        int num = 1, max1st = 0, max2nd = 0;
        int count = 1;
        System.out.println("This program allows the user to create a list integers until the user enters 0");
        System.out.println("The program will print the Largest value and the Second largest value from the list!");
        while(num != 0) {
            System.out.print("Integer No." + count + " ");
            num = sc.nextInt();

            if(num >= max1st && num >= max2nd) {
                max1st = num;
            }
            if(num >= max2nd && num < max1st) {
                max2nd = num;
            }
            count++;
        }
        System.out.println("The largest value is " + max1st);
        System.out.println("The second largest value is " + max2nd);

   }
}

I have tried to use this code.

 if(num >= max2nd && num <= max1st) {
max2nd = num;
            }

however when I run the program https://imgur.com/a/YMxj9qm - this shows.

It should print 75 and 45 . What can I do to meet the first condition and meet the second condition?

Torsten Fehre :

If you exceed your maximum number (max1st), your new maximum number will be set to num. But your second largest number will be the current maximum number. So try this condition:

if (num > max1st) {
    max2nd = max1st;
    max1st = num;
} else if (num > max2nd) {
    max2nd = num;
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=138584&siteId=1