Wednesday, 17 December 2014

// The "UsingArraysExample3" class.  Page 315-316.
// (from the Carter book)

// Example 3:
//
// The method called "swap" shown below will switch the values
// of 2 elements in an array (called "list") of double values.

public class UsingArraysExample3
{
    // "swap" changes the values of list using i and j
    // to refer to the element numbers (and their values):
    public static void swap (double[] list, int i, int j)
    {
        double temp = list [i];
        list [i] = list [j];
        list [j] = temp;
    } // swap method


    // call the method "swap" from "main":
    public static void main (String[] args)
    {
        System.out.println ("Using Arrays - Example 3");
        System.out.println ();
        int i = 4, j = 4;
        double[] list = {7.3, 9.1, 3.3, 4.7, 6.0};
        // before "swap" was called:
        System.out.println ("Before:\n");
        for (int a = 0 ; a < list.length ; a++)
        {
            System.out.println (list [a]);
        } // end of for loop # 1

        swap (list, 1, 4);

        System.out.println ();
        System.out.println ("After:\n");
        // after "swap" was called:
        for (int a = 0 ; a < list.length ; a++)
        {
            System.out.println (list [a]);
        } // end of for loop # 2

    } // main method
} // UsingArraysExample3 class

No comments:

Post a Comment