Title: Arrays Miscellaneous
Course: CPS 161: An Intro to Programming with Java - DL MM MASTER

Arrays Miscellaneous

1. Setting one array reference equal to another:


  double[] a = new double[5];
  double[] b = new double[5];
  for (int i=0; i < a.length; i++)
      a[i] = i;
	
  b=a;
  a[2] = 100;
  for (int i=0; i < a.length; i++)
      System.out.println("a["+i+"]=" + a[i]);
	
  for (int i=0; i < b.length; i++)
      System.out.println("b["+i+"]=" + b[i]);


2. Parameters for main - test this out :
public static void main (String[] args) - Normally in Eclipse you have no command line parameters.

From a Command line and outside of Eclipse you can see the parameters.
To simulate the command line parameters in Eclipse select "run as/Run Configurations".
Make sure your program is showing up in the "Main tab". Click on the Arguments tab and enter in your Program Arguments. Click "Apply" and then click "Run".

public class Test {
    public static void main(String[] args) {
         System.out.println("args.length=" +args.length);

         for (int i=0; i < args.length; i++)
             System.out.println("args[" + i + "]=" + args[i]);
    }
}


3. For the next examples, it will useful to methods that print out the contents of an array of ints and/or an array of chars:


  public void printArr(int[] arr)
    {
        for (int i=0; i < arr.length; i++)
        {
            System.out.println(arr[i]);
        }
        System.out.println("****************************");
    }
    public void printArr(char[] arr)
    {
        for (int i=0; i < arr.length; i++)
        {
            System.out.println(arr[i]);
        }
        System.out.println("****************************");
    }


4. A method returning an array:


    int[] sequentialNumbers(int max)
    {
        int[] x = new int[max+1]; // To hold numbers from 0, 1, ... , max
        for (int i=0; i < x.length; i++)
            x[i]= i;

        return x;
    }


5. Another example of a method can returning an array of upper cased letters.


  public char[] upperCaseVersion(char[] a)
  {
      char[] temp = new char[a.length];
	     char i;
	     for (i=0; i < a.length; i++)
	         temp[i] = Character.toUpperCase(a[i]);
		
	     return temp;
  }


6. Create a method which returns an array of characters containing the alphabet

    public char[] alphabet()
    {
        int len = 26;
        char[] alphs = new char[len];
        char c = 'a';
        for (int i=0; i < len; i++)
        {
            alphs[i] = c;
            c += 1;
        }
        return alphs;
    }


7. Create a method which returns an array filled with random numbers



    public int[] randArray(int max, int num)
    {
        // Numbers will be between 1 and max
        int[] rArr = new int[num];

        for (int i=0; i < num; i++)
        {
            rArr[i] = (int)(1+ max * Math.random());
        }

        return rArr;
    }


8. A main which calls all of the above:


    public static void main(String[] args) {
        Test t = new Test();

        int[] seqArr = t.sequentialNumbers(6);
        t.printArr(seqArr);

        char[] inputChars = {'t', 'i', 'g', 'e', 'r', 's'};
        char[] outputChars = t.upperCaseVersion(inputChars);
        t.printArr(outputChars);

        char[] alphabet = t.alphabet();
        t.printArr(alphabet);

        int[] rand = t.randArray(100, 10);
        t.printArr(rand);


    }


Self Test Exercises:

1. What is wrong with the following piece of code?


  int[] sampleArray = new int[10];
  for (int index=1; index <= sampleArray.length; index++)
      sampleArray[index] = 3 * index;


2. Suppose we expect the elements of the array a to be ordered so that
a[0] <= a[1] <= a[2] <= ....

However, to be safe we want our program to test the array and issue a warning in case it turns out that some elements are out of order. The following code is supposed to output sucha a warning, but it contains a bug; what is the bug?


	double[] a = new double[10];
	<Some code to fill the array a goes here>
	for (index = 0; index < a.length; index++)
	     if (a[index] > a[index+1])
		     System.out.println(" Elements out of order");
	

3. Write a method named outOfOrder that takes as a parameter an array of double and returns a value of type int. This method will test the arry for being out of order, meaning that the array violates the condition:

a[0] <= a[1] <= a[2] <= a[3] <= ....

The method returns -1 if the elements are not out of order; otherwise, it returns the index of the first element of the array that is out of order.

public class Test {

    int outOfOrder(int[] arr)
    {
        for (int i=0; i < arr.length-1; i++)
        {
            if (arr[i] > arr[i+1])
                return i;
        }
        return -1;
    }

    public static void main(String[] args) {
        Test t = new Test();

        int[] arr1 = { 1, 2, 3, 4, 5, 6, 7, 100, 110, 120, 140, 150, 200, 201, 300, 10000};
        System.out.println("outOfOrder(arr1)= " +   t.outOfOrder(arr1));


        int[] arr2 = { 1, 2, 4, 4, 4, 9, 7, 100, 110, 120, 140, 150, 200, 201, 300, 10000};
        System.out.println("outOfOrder(arr2)= " +   t.outOfOrder(arr2));


    }
}


4. Consider the following class definition:


  public class SomeClass
  {
     public static void  doSomething(int n)
	    {
	      System.out.println("doSomething(int n)");
	    }
     public void doSomethingElse(int n)
     {
       System.out.println("doSomethingElse(int n)");
     }

     public void doSomethingElseArr(int[] arr)
     {
        System.out.println("doSomethingElseArr(int[] arr)");
     }
	 <Some other code>
  }


Which of the following are acceptable method calls?

public class Test {

    public static void main(String[] args) {
        int[] a={4,5,6};
        int number =2;
        SomeClass sc = new SomeClass();

        SomeClass.doSomething(number);
        SomeClass.doSomething(a[2]);
        SomeClass.doSomething(a[3]);
        SomeClass.doSomething(a[number]);
        SomeClass.doSomething(a);
        SomeClass.doSomethingElse(number);

        sc.doSomethingElse(number);
        sc.doSomethingElseArr(number);
        sc.doSomethingElseArr(a);


    }
}
	

5. What is wrong with the doubleSize definition? It will compile but does not work as you might hope:

public class Test {

    public  void doubleSize(int[] b)
    //public int[] doubleSize(int[] b)
    {
        int[] a= new int[b.length *2];
        for(int i=0; i < b.length; i++)
            a[i] = b[i];

        b = a;
        printArr(b);
        // return b;
    }
    public void printArr(int[] arr)
    {
        for (int i=0; i < arr.length; i++)
        {
            System.out.println(arr[i]);
        }
        System.out.println("****************************");
    }

    public static void main(String[] args) {
        Test t = new Test();

        int[] arr={1,2,3};
        t.printArr(arr);

        t.doubleSize(arr);
        // arr = t.doubleSize(arr);
        t.printArr(arr);


    }
}

	

6. What is wrong with the following method definition?


  public static char[] upperCaseVersion(char[] a)
  {
      for (int i=0; i < a.length; i++)
	        a[i] = Character.toUpperCase(a[i]);
	
      return a;
  }


Exercises: These are not assigned, but practice opportunities with arrays

1. Compute standard deviation for an array of numbers
2. Create an random array of numbers and then print out a listing of each unique number along with the number of occurences of the number.
3. In a room of N people what is the probability of at least 2 people having the same birthday. We will solve this by simulation. We will create an array of N random birthdays. We will then see if there is a duplicate in the array. We will then do this experiment 100,000 times and see how many times we get a duplicate out of 100,000.
4. Given an array of random numbers, write a routine which creates another array with all of the duplicate numbers removed.
5. Write a program that reads in Rectangles. Store the rectangles in an array of Rectangles. Compute the area of all of the rectangles in the array.

Java Practice(JPHQ):

1. (5 points) Primitive Array practice - The AreaComputation program prompts the user for the number of desired rectangles. Then the user is prompted for the width and height of each desired rectangle. Then the program computes the sum of the area of all rectangles. Note that we have 2 arrays of primitives (widths and heights) to store the values.

Your Job is to provide code wherever the program says:
// ******* FILL IN CODE ********


import java.util.Scanner;

public class AreaComputation {
    double[] widths;
    double[] heights;

    Scanner keyboard = new Scanner(System.in);

    void readInRectangles()
    {
        System.out.println("Enter number of rectangles:");
        int num = keyboard.nextInt();

        // *******  FILL IN CODE ********
        // Allocate space in widths and heights arrays to hold num values

        for (int i=0; i < num; i++)
        {
            double w, h;
            System.out.println("Enter in the Rectangle width: ");
            w = keyboard.nextDouble();
            System.out.println("Enter in the Rectangle height: ");
            h = keyboard.nextDouble();

            // ******* FILL IN CODE **********
            // Update the widths and heights arrays with w and h values
        }
    }

    double computeArea()
    {
        double totalArea =0.0;

        // ******* FILL IN CODE **********
        // Compute the total area of the Rectangles represented in the arrays widths and heights

        return totalArea;
    }





    public static void main(String[] args) {


        AreaComputation ac = new AreaComputation();
        ac.readInRectangles();

        double totalArea = ac.computeArea();
        System.out.println("Total Area = "+ totalArea);

    }

}



2. (10 points) Rectangle Array practice - This program does the same work as the previous AreaComputation.java program. However, this program uses an array of Rectangles to do the work. So again your job is to provide code wherever the program says:
// ******* FILL IN CODE ********


import java.util.Scanner;

class Rectangle
{
    double width, height;
    Rectangle(double width, double height)
    {
        this.width = width;
        this.height = height;
    }
    double area()
    {
        return width * height;
    }
}

public class AreaComputation2 {
    Rectangle[] rectangles;

    Scanner keyboard = new Scanner(System.in);

    void readInRectangles()
    {
        System.out.println("Enter number of rectangles:");
        int num = keyboard.nextInt();

        // *******  FILL IN CODE ********
        // Allocate space for the rectangles array to hold num Rectangles

        for (int i=0; i < num; i++)
        {
            double w, h;
            System.out.println("Enter in the Rectangle width: ");
            w = keyboard.nextDouble();
            System.out.println("Enter in the Rectangle height: ");
            h = keyboard.nextDouble();

            // ******* FILL IN CODE **********
            // Construct a Rectangle class and store in the rectangles array
        }
    }

    double computeArea()
    {
        double totalArea =0.0;

        // ******* FILL IN CODE **********
        // Compute the total area represented in the rectangles classes
        //      by calling the area method

        return totalArea;
    }





    public static void main(String[] args) {


        AreaComputation2 ac = new AreaComputation2();
        ac.readInRectangles();

        double totalArea = ac.computeArea();
        System.out.println("Total Area = "+ totalArea);

    }

}




Last Modified: December 6, 2014 2:52 PM