Help: Working With Arrays


Help is available for each task, or you can go straight to the solution source code.

Task 1

Starting with an empty Scrapbook page, define an array of strings called colors containing the values yellow, red, and blue. Then write the Java statements needed to print the length and contents of the array to the Console.

To open an empty Scrapbook page, click on your Workspace window and select the menu-item Window->Scrapbook.

To print the contents of the array, use a for loop, just as in C++. Use the length variable of the array as the upper bound. Remember that in Java, as in C++, array indexes start at 0. Use the method System.out.println to print the arguments, which are Strings.

To execute the code, select all the text with the mouse or use the menu-item Edit->Select all then select the menu-item Edit->Run. A console window should open with the output from your program. Note that output to the console is saved (between subsequent runs) unless you clear it via Edit->Clear

Task 2

Extend the example further by creating a new array, and initializing it with the contents of the colors array. Use either a for loop, as in C++, or System.arraycopy. To use arraycopy, refer to the API for System. Then visualize the array with the inspector by including a return statement.
Create an array variable and assign to it a new array, whose length is the same as the colors array. Then use a loop to copy each element.

To use the Inspector, include the statement return(copy);, for example, at the end of your program, and instead of using Edit->Run to run the example, use Edit->Inspect


Copyright © 1996-1997 MageLang Institute. All Rights Reserved.