// (from the Carter book)
// Example 2:
//
// The method "join" creates a new array that contains the
// elements of each of the method's parameters and returns
// a reference to that array.
// Take a look at the code below, which illustrates this:
public class UsingArraysExample2A
{
// this is the static method called "join" described above,
// whioh will join double arrays "a" and "b" into another
// double array "result":
public static double[] join (double[] a, double[] b)
{
double[] result = new double [a.length + b.length];
int i, j, k;
// index through the "result" array and assign the values of
// the array parameter called "a" to the elements of "result"
// (the index is "i"):
for (i = 0 ; i < a.length ; i++)
{
result [i] = a [i];
} // end of for loop # 1
// do the same thing using the "b" array parameter this time -->
// (the index is "j" for the "b" array; include also another index "k"
// which is also needed to access the element #'s 3-5 in "result"):
for (j = 0, k = 3 ; j < b.length ; j++, k++)
{
result [k] = b [j];
} // end of for loop # 2
// output all elements of "result" (element #'s 0-5):
System.out.println ("the 'result' array element #'s and values:");
for (int n = 0 ; n < result.length ; n++)
{
System.out.println (n + "\t" + result [n]);
} // end of for loop # 3
// return the array 'result' to the "main" method:
return result;
} // join method
// this is the "main" method, which calls the method
// called "join"
public static void main (String[] args)
{
System.out.println ("Using Arrays - Example 2");
System.out.println ();
// declare 2 arrays, "a" and "b", in the "main" method;
// these 2 double arrays will then be passed as parameters to
// the method "join":
double[] a = {0.0, 0.1, 0.2};
double[] b = {1.0, 1.5, 2.5};
double[] result = new double [a.length + b.length];
System.out.println ("Now, here is the new 'result' double array: ");
System.out.println ();
// call the method "join" and pass to it (by reference) the "a"
// array and the "b" array as parameters to the "join" method:
join (a, b);
} // main method
} // UsingArraysExample2A class
No comments:
Post a Comment