+ 1

Java

Write a program that reads integers, finds the largest of them, and counts its occurrences. Assume that the input ends with number 0. Suppose that you entered 3 5 2 5 5 5 0; the program finds that the largest is 5 and the occurrence count for 5 is 4. Hint: Maintain two variables, max and count. max stores the current max number and count stores its occurrences. Initially, assign the first number to max and 1 to count. Compare each subsequent number with max. If the number is greater than max, assign it to max and reset count to 1. If the number is equal to max, increment count by 1. Sample Run 1 Enter an integer (0: for end of input): 3 Enter an integer (0: for end of input): 5 Enter an integer (0: for end of input): 2 Enter an integer (0: for end of input): 5 Enter an integer (0: for end of input): 5 Enter an integer (0: for end of input): 5 Enter an integer (0: for end of input): 0 The largest number is 5 The occurrence count of the largest number is 4 Sample Run 2 Enter an integer (0: for end of input): 0 No numbers are entered except 0 Class Name: Exercise05_41 If you get a logical or runtime error, please refer https://liveexample.pearsoncmg.com/faq.html.

12th Oct 2021, 3:48 PM
Abhishek Kutwal
Abhishek Kutwal - avatar
4 Answers
+ 3
In Sololearn we look first for an attempt with the question about a problem by solving. So please save your code on SL Playground and link here with your question.
12th Oct 2021, 3:55 PM
JaScript
JaScript - avatar
+ 2
The problem is you use variable number in while loop without an value. Updated code: https://code.sololearn.com/c24TOFx7tif4/?ref=app
12th Oct 2021, 4:11 PM
JaScript
JaScript - avatar
+ 1
Hi, I have already solved the code but it shows some errors,s please check. import java.util.Scanner; public class Exercise_05_41 { public static void main(String[] args) { Scanner input = new Scanner(System.in); // Prompt the user to enter number System.out.print("Enter numbers: "); int max = input.nextInt(); // Assign the first number to max int count = 1; // Assign 1 to count int number; // Holds future inputs // Assume that the input ends with number 0 while (number > 0) { number = input.nextInt(); if (number > max) { max = number; count = 1; } if (number == max) count++; } // Display to results System.out.println("The largest number is " + max); System.out.println( "The occurrence count of the largest number is " + count); } }
12th Oct 2021, 3:57 PM
Abhishek Kutwal
Abhishek Kutwal - avatar