Re: Case expression must be constant expression
Owen Jacobson wrote:
What're you working on?
Maybe someone has a better suggestion than an if ladder.
Yes, actually I was trying to make a replacement for an Enum in JRE 1.3
when I stumbled accross this "Constant in case expression" problem.
What I made to mimic an enum is a class with static final members of
itself inside (see example code below). But in this case I can't use the
ordinal in a switch statement...
Phil
--SSCE-- (notice the missing C :-)
import java.util.HashMap;
public class Month{
private final int ordinal;
private static final HashMap correspondanceMap = new HashMap();
private Month(int ordinal) {
this.ordinal = ordinal;
correspondanceMap.put(new Integer(ordinal), this);
}
public static final Month JANUARY = new Month(1);
public static final Month FEBRUARY = new Month(2);
public static final Month MARCH = new Month(3);
public static final Month APRIL = new Month(4);
public int getOrdinal(){
return ordinal;
}
public static Month byOrdinal(int ordinal){
return (Month)correspondanceMap.get(new Integer(ordinal));
}
public int hashCode() { return ordinal; }
public boolean equals(Object h_type){
if (!(h_type instanceof Month)) return false;
if ( ((Month)h_type).getOrdinal() == getOrdinal()) return true;
else return false;
}
public static void main(String[] args) {
System.out.println("April's ordinal is: " + Month.APRIL.getOrdinal());
Month m = Month.byOrdinal(2);
if(m.equals(Month.FEBRUARY)){
System.out.println("Both are equal.");
}
// switch doesn't work
int choice = 3;
switch(choice){
case Month.JANUARY.getOrdinal():
System.out.println("Do something for January");
case Month.FEBRUARY.getOrdinal():
System.out.println("Do something for February");
case Month.MARCH.getOrdinal():
System.out.println("Do something for March");
case Month.APRIL.getOrdinal():
System.out.println("Do something for April");
default:
System.out.println("None of those months");
}
}
}