Write a program that read integers, finds the largeste of them, and counts its occurrences.
Zeros stops each series.
Allow the user to go again in the same run if desired.
Zero will also stop the program.
I first wrote the inner while loop and got that portion working. For some reason if you change the else if statement to an if statement, the program doesn't work properly. I will have to figure that one out as I thought that they were interchangeable in this instance.
import java.util.Scanner;
public class OccurenceOfMaxNumbers
//read integers and find the largest and count its occurrences
{
public static void main(String[] args)
{
//Declare variables
int numbers, end, max = 0, count = 0;
do
{
//create scanner and ask for integers
Scanner input = new Scanner(System.in);
System.out.print("Enter numbers: ");
//input numbers in the while loop..zero will end
while ((numbers = input.nextInt()) != 0)
{
//if number is greater than the max it becomes max and
//count restarts at 1
if (numbers > max)
{
max = numbers;
count = 1;
}
//if the number is equal to max, count increases by one
else if (numbers == max)
{
count++;
}
}
//print results
System.out.println("The largest number is " + max);
System.out.println("The occurrence count of the largest number is " + count);
//Ask if user wants to go again, 0 to end, any key to continue
System.out.println("Do you want to end (type 0): ");
end = input.nextInt();
//reset count and max to zero
count = 0;
max = 0;
}
while (end !=0);
}
}
No comments:
Post a Comment