Take the follwoing java code and put it into a method called getCount. getCount
ID: 3797648 • Letter: T
Question
Take the follwoing java code and put it into a method called getCount. getCount receives an int array, and an int value to search for. It returns the number of times that value is found in the array and returns that number. If not found it returns 0. Create a constant to hold the size of an array: final int size = 100; Use this to create an array of 100 ints. Store in each element of the array a random number from 1 to 6, representing one of the 6 sides of a single die. Use getCount method to print out the number of times each die (1 through 6) was rolled.
import java.util.Scanner;
public class ArrayTest
{
public static void main(String[] args)
{
//array to store numbers
int[] Numbers = new int[10];
int SearchValue, count=0;
Scanner input=new Scanner(System.in);
//loop to store user inputs
for(int index = 0; index < Numbers.length; index++)
{
System.out.println("Enter a number: ");
Numbers[index]=input.nextInt();
}
//user input of value to be searched
System.out.println("Enter a value to search for: ");
SearchValue=input.nextInt();
//loop to search number
for(int index = 0; index < Numbers.length; index++)
{
if(Numbers[index]==SearchValue)
count++;
}
//loop to configure the amount of times the searched number appears
if(count>0)
{
if(count>1)
System.out.println("The value " + SearchValue +" appears "+ count +" times");
}
else
{
System.out.println("The value " + SearchValue +" does not appear in the array");
}
}
}
SAMPLE OUTPUT:
Explanation / Answer
ArrayTest.java
import java.util.Random;
import java.util.Scanner;
public class ArrayTest
{
public static void main(String[] args)
{
final int size = 100;
//array to store numbers
int[] Numbers = new int[size];
int SearchValue, count=0;
Scanner input=new Scanner(System.in);
//loop to store user inputs
Random r = new Random();
for(int index = 0; index < Numbers.length; index++)
{
Numbers[index]= r.nextInt(6)+1;
}
System.out.println("Statistics from rolling "+size+" die");
//loop to search number
for(int index = 1; index <= 6; index++)
{
count = getCount(Numbers, index);
System.out.println(index+" rolled "+count+" times");
}
}
public static int getCount(int Numbers[],int SearchValue){
int count = 0;
for(int index = 0; index < Numbers.length; index++)
{
if(Numbers[index] == SearchValue){
count++;
}
}
return count;
}
}
Output:
Statistics from rolling 100 die
1 rolled 6 times
2 rolled 20 times
3 rolled 20 times
4 rolled 18 times
5 rolled 20 times
6 rolled 16 times
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.