English Deutsch Français Italiano Español Português 繁體中文 Bahasa Indonesia Tiếng Việt ภาษาไทย
All categories

How do I select random values out of an enum?
Why wont this work?
"enum e{One, Two, Three, Four, Five};
Random r = new Random();
e myEnum = r.nextInt(4);"

2007-05-29 01:13:49 · 3 answers · asked by chase 3 in Computers & Internet Programming & Design

3 answers

First thing, enum(s) in Java are NOT integer.
enum(s) in java are 'classes', while enum 'values' are objects.

e myEnum = r.nextInt(4);

This will try to cast a primitive type int into an object of the class 'e'.
It won't work.

Try this:

int n = r.nextInt(4);
e[] values = e.values(); // this static method will get an array of 'e'
e eVal = values[n];

Tip: enums are a kind of classes, as a naming convention they should start with uppercase.

2007-05-29 01:41:18 · answer #1 · answered by minus71 2 · 1 0

You will probably find the answer to your question on this link.

2007-05-29 01:37:08 · answer #2 · answered by AnalProgrammer 7 · 0 0

72f8ab13f56f855e98eea6e73251c1f72f8ab13f56f855e98eea6e73251c172f8ab13f56f855e98eea6e73251c172f8ab13f56f855e98eea6e73251c1understand72f8ab13f56f855e98eea6e73251c1your72f8ab13f56f855e98eea6e73251c1problem72f8ab13f56f855e98eea6e73251c1correctly,72f8ab13f56f855e98eea6e73251c172f8ab13f56f855e98eea6e73251c1f72f8ab13f56f855e98eea6e73251c1you72f8ab13f56f855e98eea6e73251c1had72f8ab13f56f855e98eea6e73251c1an72f8ab13f56f855e98eea6e73251c1array72f8ab13f56f855e98eea6e73251c1of72f8ab13f56f855e98eea6e73251c1enum,72f8ab13f56f855e98eea6e73251c1then72f8ab13f56f855e98eea6e73251c172f8ab13f56f855e98eea6e73251c1t72f8ab13f56f855e98eea6e73251c1should72f8ab13f56f855e98eea6e73251c1be72f8ab13f56f855e98eea6e73251c1a72f8ab13f56f855e98eea6e73251c1s72f8ab13f56f855e98eea6e73251c1mple72f8ab13f56f855e98eea6e73251c1th72f8ab13f56f855e98eea6e73251c1ng72f8ab13f56f855e98eea6e73251c1to72f8ab13f56f855e98eea6e73251c1generate72f8ab13f56f855e98eea6e73251c1a72f8ab13f56f855e98eea6e73251c1random72f8ab13f56f855e98eea6e73251c1[72f8ab13f56f855e98eea6e73251c172f8ab13f56f855e98eea6e73251c172f8ab13f56f855e98eea6e73251c1]72f8ab13f56f855e98eea6e73251c172f8ab13f56f855e98eea6e73251c1n72f8ab13f56f855e98eea6e73251c1the72f8ab13f56f855e98eea6e73251c1range72f8ab13f56f855e98eea6e73251c1of72f8ab13f56f855e98eea6e73251c1that72f8ab13f56f855e98eea6e73251c1array,72f8ab13f56f855e98eea6e73251c1the72f8ab13f56f855e98eea6e73251c1arr.length;

2016-10-30 01:43:08 · answer #3 · answered by Anonymous · 0 0

fedest.com, questions and answers