Java Reference
In-Depth Information
myList[
2
] =
3.4
;
myList[
3
] =
3.5
;
Caution
The
new
operator is not used in the array-initializer syntax. Using an array initializer, you
have to declare, create, and initialize the array all in one statement. Splitting it would
cause a syntax error. Thus, the next statement is wrong:
double
[] myList;
myList = {
1.9
,
2.9
,
3.4
,
3.5
};
7.2.6 Processing Arrays
When processing array elements, you will often use a
for
loop—for two reasons:
All of the elements in an array are of the same type. They are evenly processed in the
same fashion repeatedly using a loop.
■
Since the size of the array is known, it is natural to use a
for
loop.
■
Assume the array is created as follows:
double
[] myList =
new double
[
10
];
The following are some examples of processing arrays.
1.
Initializing arrays with input values:
The following loop initializes the array
myList
with user input values.
java.util.Scanner input =
new
java.util.Scanner(System.in);
System.out.print(
"Enter "
+ myList.length +
" values: "
);
for
(
int
i =
0
; i < myList.length; i++)
myList[i] = input.nextDouble();
2.
Initializing arrays with random values:
The following loop initializes the array
myList
with random values between
0.0
and
100.0
, but less than
100.0
.
for
(
int
i =
0
; i < myList.length; i++) {
myList[i] = Math.random() *
100
;
}
3.
Displaying arrays:
To print an array, you have to print each element in the array using a
loop like the following:
for
(
int
i =
0
; i < myList.length; i++) {
System.out.print(myList[i] +
" "
);
}
Tip
For an array of the
char[]
type, it can be printed using one print statement. For exam-
ple, the following code displays
Dallas
:
print character array
char
[] city = {
'D'
,
'a'
,
'l'
,
'l'
,
'a'
,
's'
};
System.out.println(city);
4.
Summing all elements:
Use a variable named
total
to store the sum. Initially
total
is
0
. Add each element in the array to
total
using a loop like this:
double
total =
0
;
for
(
int
i =
0
; i < myList.length; i++) {
total += myList[i];
}
Search WWH ::
Custom Search