Java Reference
In-Depth Information
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];
}
5.
Finding the largest element:
Use a variable named
max
to store the largest element. Ini-
tially
max
is
myList[0]
. To find the largest element in the array
myList
, compare
each element with
max
, and update
max
if the element is greater than
max
.
double
max = myList[
0
];
for
(
int
i =
1
; i < myList.length; i++) {
if
(myList[i] > max) max = myList[i];
}
6.
Finding the smallest index of the largest element:
Often you need to locate the
largest element in an array. If an array has more than one largest element, find the
smallest index of such an element. Suppose the array
myList
is {
1
,
5
,
3
,
4
,
5
,
5
}.
The largest element is
5
and the smallest index for
5
is
1
. Use a variable named
max
to store the largest element and a variable named
indexOfMax
to denote the index
of the largest element. Initially
max
is
myList[0]
, and
indexOfMax
is
0
. Compare
each element in
myList
with
max
, and update
max
and
indexOfMax
if the element
is greater than
max
.
double
max = myList[
0
];
int
indexOfMax =
0
;
for
(
int
i =
1
; i < myList.length; i++) {
if
(myList[i] > max)
{
max = myList[i];
indexOfMax = i;
}
}
7.
Random shuffling:
In many applications, you need to randomly reorder the ele-
ments in an array. This is called
shuffling
. To accomplish this, for each element
VideoNote
Random shuffling