Returns the ordinal of this enumeration constant (its position in its enum declaration, where the initial constant is assigned an ordinal of zero). Most programmers will have no use for this method. It is designed for use by sophisticated enum-based data structures, such as EnumSet and EnumMap.
Your code have some issue. I have to modified the line below
case C: Roman.L;break;
to avoid compilation error by adding "t =" statement
case C: t = Roman.L;break;
After that I compiled and ran the code. I get an output 21.
Now, your question is about ordinal(). I cut and paste a definition of the ordinal method (see below) from java.sun.com/j2se/1.5.0/docs/api
"Returns the ordinal of this enumeration constant (its position in its enum declaration, where the initial constant is assigned an ordinal of zero)."
I hope I explain this correctly. Here goes...
In your code the ordinal sequence is I = 0 V = 1 X = 2 L = 3 C = 4 M = 5
To test out this theory, I inserted a statement "System.out.println(t.ordinal());" after "Roman t = Roman.X;" statement. The output is 2, because Roman.X ordinal (order sequence) is 2 (see ordinal sequence above). This verifies that the theory is correct.
Next, I ran a debugger and monitor the while loop. The statement "case L: if(t.ordinal()>2) z+=5;" iterated through the while loop three times. It does this because of the x<10 condition.
[The 1st pass] t.ordinal() = 4 because t = Roman.C, z = 10, and x = 8 [The 2nd pass] t.ordinal() = 3 because t = Roman.L then break out, Z = 15, and x = 9 [The 3rd pass] t.ordinal() = 3 because t = Roman.L then break out, z = 20, and x = 10
Your while(x<10) condition becomes false because x = 10.
guys please help how the z value became 10 on the first pass itself,but from my calculations z value is coming 8,
- start: x == 7, z == 2, roman == X
- iteration 1: roman == X so roman = C, z += 5, x++, and another z++. At the end, x == 8, z == 8 and roman == C
I’ve looked at a lot of different solutions, and in my humble opinion Aspose is the way to go. Here’s the link: http://aspose.com