星期五, 六月 10, 2005

Java constant expression required issue:

constant expression:发生在用Switch ...case的时候使用了静态variable.

如下:
class Tester {
public static int a = 1;
public static int b = 2;

public static void main(String[] args) {
int x = a;
switch(x) {
case a: System.out.println("matched a==0");
break;
case b: System.out.println("matched b==1");
break;
}
}}
得到:
C:\temp>javac Tester.java
Tester.java:8: constant expression required
case a: System.out.println("matched a==0");
^
Tester.java:10: constant expression required
case b: System.out.println("matched b==1");


方法修改static 变量为final static: 如下
class Tester {

public final static int a = 1;
public final static int b = 2;


public static void main(String[] args) {
int x = a;
switch(x) {
case a: System.out.println("matched a==0");
break;
case b: System.out.println("matched b==1");
break;
}
} // main()
} // Tester_2