In: Computer Science
Consider the following class TestScores. All the methods have direct access to the scores array. Please type in the answers here.
|
TestScores |
|
|
Write the constructor method. It fills the array with random number from 0 -100. Find below the code to get you started.
public TestScores ()
{
Random rand = new Random();
for(int i = 0; i < SIZE ; i++)
{
scores[i] = rand.nextInt(101);
}
}
Finding the maximum value in an array. Write the method findMax. It returns the maximum value in the array.
Finding the minimum value in an array. Write the method findMin. It returns the minimum value in the array.
Write the method countScores. The method returns the number of exams where the score is greater or equal to 90. This is an example of a linear search.
Write the method called findScore that accepts one int value. The method should check if the value exists in the array and if it does it returns true. Otherwise, the method should return false.
import java.util.Random;
public class TestScores {
public int[] testScores;
public int SIZE = 10;
// constructor accepts an array and tests it for valid
scores (between 0 - 100)
public TestScores ()
{
testScores = new int[SIZE];
Random rand = new Random();
for(int i = 0; i < SIZE ; i++)
{
testScores[i] = rand.nextInt(100);
}
}
// the method countScores. The method returns the
number of exams where the score is greater or equal to 90
public int countScores() {
int count = 0;
for (int index = 0; index <
testScores.length; index++)
{
if(testScores[index]>=90) count++;
}
return count;
}
//the method called findScore that accepts one int
value. The method should check if the value exists in the array and
if it does it returns true.
public boolean findScore (int val) {
int count = 0;
for (int index = 0; index <
testScores.length; index++)
{
if(testScores[index]==val) return true;
}
return false;
}
//Finding the maximum value in an array. Write the
method findMax. It returns the maximum value in the array.
public int findMax() {
int max = testScores[0];
for (int index = 1; index <
testScores.length; index++)
{
if(testScores[index]>max) {
max = testScores[index];
}
}
return max;
}
//Finding the minimum value in an array. Write the
method findMin. It returns the minimum value in the array
public int findMin() {
int min = testScores[0];
for (int index = 1; index <
testScores.length; index++)
{
if(testScores[index]<min) {
min = testScores[index];
}
}
return min;
}
public static void main(String[] args) {
TestScores obj = new
TestScores();
System.out.println("Max -
"+obj.findMax());
System.out.println("Min -
"+obj.findMin());
System.out.println("10 presence in
the array - "+obj.findScore(10));
System.out.println("Scores greater
than 90 = "+obj.countScores());
}
}
