Here is the problem : Write a program that reads integers, finds the TWO (2) lar
ID: 3538077 • Letter: H
Question
Here is the problem : Write a program that reads integers, finds the TWO (2) largest of them, and counts their occurrences. Here is a sample of the program: Enter numbers: 3 5 2 5 5 5 0 The largest number is 5 The occurrence count of the largest number is 4 The second largest number is 3. The occurrence count of the second largest number is 1. I can get the largest integer t read and count, I am having trouble gettign the program to find the second largest and count its occurances. Here is what i have: import java.util.Scanner; public class Integers { public static void main(String [] args) { Scanner input = new Scanner(System.in); int max = 1; int max1 = 0; int count = 0; int count1 = 0; //prompt user for number System.out.print("Please enter a few numbers with spaces(0 should be your last entry): "); int number = input.nextInt(); //loop to find the largest number and its occurance while (number != 0) { if (number > max){ count = 1; max = number; } else if (max == number) count++; number = input.nextInt(); } System.out.println("The largest number is: " + max); System.out.println("The occurance count of the largest number is: " + count); // finds the second largest number while (number != 0) { if (number < max){ count = 1; max = number; } else if (max == number) count1++; number = input.nextInt(); } System.out.println("The second largest number is: " + max1); System.out.println("The occurance count of the second largest number is: " + count1); } }Explanation / Answer
Try the following loop, I've checked it, it works! :)
int count1=count2=0;
int max1=0; int max2=0;
int number= input.nextInt();
while(number!=0)
{if (number > max1)
{max1=number;
max2=max1; count2=count1;
count1=1;
}
else if(number<max1 && number>max2)
{max2=number;
count2=1;
}
if (max1==number) count1++;
if (max2==number) count2++;
number= input.nextInt();
}
System.out.println("Laregest number" + max1 + "occurs" + count1 + "times");
System.out.println("Second laregest number" + max2 + "occurs" + count2 + "times");