Could someone please help me with the following; Write a program that reads the
ID: 3628584 • Letter: C
Question
Could someone please help me with the following;Write a program that reads the integers between 1 and 100 and counts the occurences of each. Assume the input ends with 0. You should have two additional methods besides main. Their signature is:
public static void displayResults(int[] numList) - This method displays the results as shown below.
public static int getValidInput() - This method gets the input from the keyboard, makes sure it falls between 1 and 100 and if so returns the number to the calling function. If the number does not meet the criteria, then it should show an error message to the user and prompt for the number again.
Here is a sample run of the program:
Enter a number from 1 to 100. Enter 0 to end.
2
Enter a number from 1 to 100. Enter 0 to end.
5
Enter a number from 1 to 100. Enter 0 to end.
6
Enter a number from 1 to 100. Enter 0 to end.
5
Enter a number from 1 to 100. Enter 0 to end.
4
Enter a number from 1 to 100. Enter 0 to end.
3
Enter a number from 1 to 100. Enter 0 to end.
23
Enter a number from 1 to 100. Enter 0 to end.
43
Enter a number from 1 to 100. Enter 0 to end.
2
Enter a number from 1 to 100. Enter 0 to end.
0
A total of 9 numbers were entered.
The number 2 occurs 2 times
The number 3 occurs 1 time
The number 4 occurs 1 time
The number 5 occurs 2 times
The number 6 occurs 1 time
The number 23 occurs 1 time
The number 43 occurs 1 time
Explanation / Answer
import java.util.Scanner;
public class ReadIntegers
{
private static Scanner kb;
public static void main(String[] args)
{
kb = new Scanner(System.in);
private int[] list = new int[101];
int num;
int count = 0; // count # entered
// stop at 0
while((num = getValidInput()) > 0)
{
// update count
count++;
// record number
list[num]++;
}
// print displayed numbers
System.out.println("A total of "+count+" numbers were entered.");
displayResults(list);
}
public static void displayResults(int[] numList)
{
for(int i = 1; i < numList.length; i++)
{
if(numList[i] > 1)
System.out.println("The number "+i+" occurs "+numList[i]+" times");
else if(numList[i] == 1)
System.out.println("The number "+i+" occurs 1 time");
}
}
public static int getValidInput()
{
while(true)
{
System.out.println("Enter a number from 1 to 100. Enter 0 to end.");
int num = kb.nextInt();
if(num >= 0 && num <= 100)
return num;
else
System.out.println("Invalid.");
}
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.