Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>The reason that this doesn't work is that your <code>if</code> statements are testing whether the array that enumerates all <code>RandomNumbers</code> instances is equal to some <code>String</code>. Of course, it never could be. When you call <code>randN.values()</code>, you are actually invoking the static method <code>RandomNumbers.values()</code>, the same method you used in your <code>getRandom()</code> method. If you want a string that you can compare, <code>randN.name()</code> would work, but it's really not a good idea.</p> <p>If you insist on comparing something, you should use an identity comparison, like this:</p> <pre><code>int num; /* Notice I'm not prematurely assigning meaningless garbage here. */ if (randN == RandomNumbers.ONE) num = 1; else if(randN == RandomNumbers.TWO) num = 2; else if(randN == RandomNumbers.THREE) num = 3; else throw new IllegalArgumentException("Unrecognized RandomNumber: " + randN); </code></pre> <p>The next step forward would be to use a <code>switch</code> statement:</p> <pre><code>int num; switch(randN) { case ONE: num = 1; break; case TWO: num = 2; break; case THREE: num = 3; break; default: throw new IllegalArgumentException(); } </code></pre> <p>You aren't making good use of an enum. Here's an approach that takes full advantage of an <code>enum</code> type:</p> <pre><code>public enum RandomNumber { ONE(1), TWO(2), THREE(3); private final int value; private RandomNumber(int value) { this.value = value; } public int getValue() { return value; } public static RandomNumber roll() { RandomNumber[] values = values(); int idx = ThreadLocalRandom.current().nextInt(values.length); return values[idx]; } public static void main(String... argv) { RandomNumber num = RandomNumber.roll(); System.out.printf("The random number is %s (%d).%n", num, num.getValue()); } } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload