Java Reference
In-Depth Information
To get the full potential from an enumerated type, you need some way to cycle
through all its values. The static method
values( )
provides you with that ability. This
method returns an array whose elements are the values of the enumerated type, and is
provided automatically for every enumerated type. Display 6.15 gives a simple example
of using the method
values( )
to cycle through all the values in an enumerated type.
(This is one situation where it is much cleaner to use a for-each loop instead of an
ordinary
for
loop. If you have read the starred section on the for-each loop, be sure to
do Self-Test Exercise 22, which redoes Display 6.15 using a for-each loop.)
The
values
Method
Every enumerated type has a static method named
values( )
, which returns an array
whose elements are the values of the enumerated type in the order in which they are
listed in the definition of the enumerated type. The base type for the array returned is the
enumerated type. See Display 6.15 for an example.
Display 6.15
The Method
values
(part 1 of 2)
1
import
java.util.Scanner;
2
3
public class
EnumValuesDemo
4 {
5
enum
WorkDay {MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY};
6
public static void
main(String[] args)
7 {
8 WorkDay[] day = WorkDay.values();
9 Scanner keyboard =
new
Scanner(System.in);
10
double
hours = 0, sum = 0;
This is equivalent to
day[i].toString().
11
for
(
int
i = 0; i < day.length; i++)
12 {
13 System.out.println("Enter hours worked for " + day[i]);
14 hours = keyboard.nextDouble();
15 sum = sum + hours;
16 }
17 System.out.println("Total hours work = " + sum);
18 }
19 }