In: Computer Science
1. Add code to the constructor which instantiates a testArray that will hold 10 integers.
2. Add code to the generateRandomArray method which will fill testArray with random integers between 1 and 10
3. Add code to the printArray method which will print each value in testArray.
4. Write an accessor method, getArray which will return the testArray
Here's the code starter code:
import java.util.ArrayList;
public class TestArrays
{
private int[] testArray;
public TestArrays()
{
}
public void generateRandomArray()
{
}
public void printArray()
{
}
}
Below is the code and screenshots .
TestArrays.java
-----------------------------------------------------
/*
* This class fills the array with 1 to 10 random numbers
* and prints the each value in the array.
*/
import java.util.ArrayList;
public class TestArrays
{
private int[] testArray;
private int arraylength;
public TestArrays(int x)
{
arraylength= x;
}
/*
* Method to fill the array with random
numbers from 1 to 10.
*/
public void generateRandomArray()
{
System.out.println("Populating
array with random values");
testArray = new
int[arraylength];
for(int
i=0;i<testArray.length;i++)
{
testArray[i] =
(int) (Math.random()*10);
}
}
/*
* This method prints the values in the
array one by one.
*/
public void printArray()
{
System.out.println("Going to print
the array values :");
for(int i=0; i<testArray.length;
i++)
{
System.out.println(testArray[i]);
}
}
/**
* getter method to return the array. This will return
array object.
* @return the testArray
*/
public int[] getTestArray() {
return testArray;
}
public static void main(String [] args) {
TestArrays t = new
TestArrays(10);
t.generateRandomArray();
t.printArray();
}
}
----------------------------------------------------------------------------------
Output:
I have writtne this code in eclipse -> It gets compiled automatically.
To run the program -> right click on it and Run as --> Java Applicaiton -
Populating array with random values
Going to print the array values :
8
2
3
7
3
6
4
8
5
3