Java Reference
In-Depth Information
Discussion
for
loop is in three parts: initialize, test, and change. If the test part is initially false, the loop
will never be executed, not even once.
For discontinuous ranges of numbers, use a
java.util.BitSet
.
The following program demonstrates all of these techniques:
public
public class
class
NumSeries
NumSeries
{
public
public static
static
void
void
main
(
String
[]
args
) {
// When you want an ordinal list of numbers, use a for loop
// starting at 1.
for
for
(
int
int
i
=
1
;
i
<=
months
.
length
;
i
++)
System
.
out
.
println
(
"Month # "
+
i
);
// When you want a set of array indices, use a for loop
// starting at 0.
for
for
(
int
int
i
=
0
;
i
<
months
.
length
;
i
++)
System
.
out
.
println
(
"Month "
+
months
[
i
]);
// For e.g., counting by 3 from 11 to 27, use a for loop
for
for
(
int
int
i
=
11
;
i
<=
27
;
i
+=
3
) {
System
.
out
.
println
(
"i = "
+
i
);
}
// A discontiguous set of integers, using a BitSet
// Create a BitSet and turn on a couple of bits.
BitSet b
=
new
new
BitSet
();
b
.
set
(
0
);
// January
b
.
set
(
3
);
// April
b
.
set
(
8
);
// September
// Presumably this would be somewhere else in the code.
for
for
(
int
int
i
=
0
;
i
<
months
.
length
;
i
++) {
iif
(
b
.
get
(
i
))
System
.
out
.
println
(
"Month "
+
months
[
i
]);
}
// Same example but shorter:
// a discontiguous set of integers, using an array