ArrayTest.java Answers

Click here to go back to the questions
// ANSWERS:

// (1) Compile and run this file and observe how
// the "fred" array is printed to the screen.

// (2) Add a line to the "doStuff" method to create a new
// array called "nums" of ten floating point numbers.  Use
// the double type for double precision floating point
// numbers.

// HINT: Look at how the fred array was created and copy the
// pattern for this.
// 

double[] nums = new double[10];

// 
// (3) In the doStuff method , write a "for" loop to set the
// elements of the nums array to the values 1.0, 1.1, 1.2,
// through to 1.9.
// 

for (int i=0; i<10; i++) {
   nums[i] = 1 + i / 10.0;
}

// 
// (4) Write a second "for" loop to print out the elements of
// the nums array to make sure that the values are what they
// are supposed to be.  Compile and run the program to find
// out.

// NOTE: Java's double and float types are incapable of
// storing some numbers exactly, so there may be some
// inexactness in the values that are printed out for this
// question.
// 

for (int i=0; i<10; i++) {
   System.out.println(nums[i]);
}

// 
// (5) Write a method: public void printArray(double[] x).
// The argument "x" is of type "double[]" so it is an array
// of double precision floating point numbers.  The method
// should use a "for" loop to print out the contents of "x".
//
// HINT: Inside the printArray method, write a "for" loop
// like the one that prints out the "fred" array, except that
// instead of writing 10 as the upper bound for the array,
// use the "length" property of the "x" array.
// 

public void printArray(double[] x) {
   for (int i=0; i<x.length; i++) {
      System.out.println(x[i]);
   }
}

// 
// (6) In the doStuff method, call the printArray method
// using the array "nums" as the argument, to see if it
// correctly prints out the "nums" array.
// 

printArray(nums);

// 
// (7) Now do the questions in the file ArrayTest2.java.