ArrayTest.java Questions

Instructions

  1. With the left mouse button pressed, drag the mouse across the contents of the program listing that is shown below. This will select the program listing. Then choose Copy from the Edit menu of your web browser to copy the program listing to the clipboard.
  2. Start your text editor and create a new file called ArrayTest.java. Choose Paste to paste the contents of the program listing from the clipboard into the new file.
  3. Save the file to disk and begin answering the questions that are shown below.
  4. When you need to look at the model answer, click here.
  5. Click here to go back to the tutorials menu.

Program listing

// ARRAYS TUTORIAL
// Copyright (C) 1998-2016 Davin Pearson
// Website: http://davin.50webs.com/java-tutorials

class ArrayTest {

   public static void main(String[] args) {
      ArrayTest x = new ArrayTest();
      x.doStuff();
   }

   public void doStuff() {

      // creates the array fred of ten integers.
      int[] fred = new int[10];

      // sets the values of the fred array
      for (int i=0; i<10; i++) {
         fred[i] = i;
      }

      // prints the values of the fred array
      for (int i=0; i<10; i++) {
         System.out.println(fred[i]);
      }

      // insert your code for the nums array here:

   }
}

// QUESTIONS:

// (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.
// 
// (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.
// 
// (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.
// 
// (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.
// 
// (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.
// 
// (7) Now do the questions in the file ArrayTest2.java.