Here’s my code snippet:
public static void main(String[] args) {
int num;
int large;
int small;
int secondLarge;
Scanner scan = new Scanner(System.in);
System.out.print("Input a number: ");
num = scan.nextInt();
large = num;
small = num;
secondLarge = num;
for (int x = 9; x > 0; x--) {
System.out.print("Enter " + x + " more number: ");
num = scan.nextInt();
if (num > large) {
large = num;
}
if (num > secondLarge) {
secondLarge = num;
}
if (secondLarge > large) {
large = secondLarge;
}
if (num < small) {
small = num;
}
}
System.out.println( large + " is the largest number, " + secondLarge + " is the second largest number and " + small + " is the smallest number!");
}
It correctly prints the smallest and largest number. But it fails when I want to print the second-largest number.
How to find the second largest element in the for loop?