Answers to Array Worksheet #2

advertisement
Answers to Array Worksheet #2
1. Write a statement that declares a reference to an array of int’s. The array
reference should be named numbers.
int[] numbers;
2. Write a statement that declares and constructs an array of Rectangle’s
named boxes so that the array stores exactly 10 Rectangle objects.
Rectangle[] boxes = new Rectangle[10];
3. Write a SINGLE statement that declares a reference to an array named
grades that stores five double's. In the same statement, initialize the
array to the values 44, 55, 66, 77, and 88.
double[] grades = {44,55,66,77,88};
4. Write a statement that assigns the value 13 to the fifth position of the array
numbers.
numbers[4]=13;
5. Write a statement that displays the value stored in the third position of the
array numbers.
System.out.println(numbers[2]);
6. Write a statement that displays the number of elements in the array named
numbers.
System.out.println(numbers.length);
7. Write a SINGLE statement that stores the value 99 into the last position of
an array named grades no matter how many elements it has.
grades[grades.length-1]=99;
8. Write a for loop that assigns the integer values 1 through 10 to the first
ten positions of an array named scores. You can assume that the array
scores has already been declared and constructed to have 10 elements.
for(int i=0; i<10; i++)
scores[i]=i+1;
9. Write a statement that declares a constructs a two-dimensional array of
int’s named sportsScores that has exactly 5 rows and 4 columns.
SKIP for now
10. Write a statement that assigns the value 13 to the element in the third row
and the second column of the two-dimensional array named
sportsScores.
SKIP for now
Complete the following exercises on the back of this worksheet.
11. Write a static method named findPosition that accepts two
parameters, an int named key and an array of int’s named myArray.
The method must return the subscript position within myArray in which
key is found. If key is not stored in myArray, return the value -1.
public static int findPosition(int keyValue, int[] myArray)
{
for(int i=0; i< myArray.length; i++)
{
if(myArray[i]==keyValue)
return i;
}
return -1;
}
12. Write a code segment that uses a for loop and an if statement to
determine whether the value 13 is stored in a previously declared twodimensional array named sportsScores. If the value 13 is stored in the
array, then store the value true in a boolean flag variable named found.
Otherwise, store false in found. The array sportsScores has 4
columns and 5 rows.
SKIP for now
Download