Problem 150
Pre-populating Arrays
We’re going to learn how to easily give starting values to an array when creating it! (These are called “array initializers”.)
Use the provided code, and get it to compile.
public class GivingAnArrayABunchOfValuesAtOnce {
public static void main(String[] args) {
String[] arr1 = {"alpha", "bravo", "charlie"};
System.out.print("The first array is filled with the following values:\n\t");
for (int i = 0; i < arr1.length; i++)
System.out.print(arr1[i] + " ");
System.out.println();
}
}
What You Should See
The first array is filled with the following values: alpha bravo charlie
After you add in the code you’re supposed to, you should see something more like this:
The first array is filled with the following values: alpha bravo charlie delta echo The second array is filled with the following values: 11 23 37 41 53
What You Should Do on Your Own
Assignments turned in without these things will receive no credit.
- The first array only has three values in it. Add two more, for a total of five.
- Create a second array of ints, and give it five starting values, too.
- Print the second array.
◄ 149: Locating the Largest Value in an Array 151: Parallel Arrays ►
Adapted from ProgrammingByDoing.com
©2013 Graham Mitchell
This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 3.0 United States License.