In: Computer Science
Write a Java program (name it LargestOccurenceCount) that reads from the user positive non-zero integer values, finds the largest value, and counts it occurrences. Assume that the input ends with number 0 (as sentinel value to stop the sentinel loop). The program should ignore any negative input and should continue to run.
Hint: to remember/save entered (good) values, you can concatenate them into a string (separated by spaces) that you can output later on.
Sample runs showing input prompts and outputs are (DO NOT read inputs as String type):
Enter positive integers (0 to quit): 3 4 5 -9 4 2 5 1 -5 2 5 0
You entered: 3 4 5 4 2 5 1 2 5
Largest value: 5
Occurrences: 3 times
Enter positive integers (0 to quit): 3 7 5 -4 4 2 -5 5 1 7 7 0
You entered: 3 7 5 4 2 5 1 7 7
Largest value: 7
Occurrences: 3 times
Document your code, and organize and space out your outputs as shown. Design your program such that it allows the user to re-run the program with different inputs in the same run (i.e., use a sentinel loop structure).
import java.util.Scanner; public class LargestOccurenceCount { public static void main(String[] args) { Scanner in = new Scanner(System.in); char ch; do { System.out.print("Enter positive integers (0 to quit): "); int largest = 0, count = 0, num; while (true) { num = in.nextInt(); if (num == 0) { break; } else if (num > largest) { largest = num; count = 1; } else if (num == largest) { count++; } } System.out.println("Largest value:\t" + largest); System.out.println("Occurrences:\t" + count + " times"); System.out.print("Do you want to try again(y or n): "); ch = in.next().charAt(0); System.out.println(); } while (ch == 'y' || ch == 'Y'); } }