Arrays and Strings
You can place strings of text into arrays. This is done in the same way as for integers:
String[ ] aryString = new String[5] ;
aryString[0] = "This";
aryString[1] = "is";
aryString[2] = "a";
aryString[3] = "string";
aryString[4] = "array";
The code above sets up a string array with 5 positions. Text is then assigned
to each position in the array.aryString[1] = "is";
aryString[2] = "a";
aryString[3] = "string";
aryString[4] = "array";
Here's a loop that goes round all the positions in the array, printing out whatever is at each position:
int i;
for ( i=0; i < aryString.length; i++ ) {
System.out.println( aryString[i] );
}
The loop goes round and round while the value in the variable called i is less than the length of the array called aryString.
When the above programme is run, the Output window will look like this:
Exercise
Set up an array to hold the following values, and in this order: 23, 6, 47, 35, 2, 14. Write a programme to get the average of all 6 numbers. (You can use integers for this exercise, which will round down your answer.)
Exercise
Using the above values, have your programme print out the highest number in the array.
Exercise
Using the same array above, have your programme print out only the odd numbers.
In the next lesson, you'll learn about multi-dimensional arrays in java.
Subscribe to:
Post Comments
(
Atom
)
No comments :
Post a Comment