[英]Java how to use global variables in switch statement
I have three integer global variables: 我有三个整数全局变量:
public static int a = 1;
public static int b = 2;
public static int c = 3;
I want to do: 我想要做:
int code = dis.readInt();
switch(code)
{
case a:
......
break;
case b:
......
break;
case c:
......
break;
}
But it is not working, can anyone help? 但这不起作用,有人可以帮忙吗? Thanks!
谢谢!
The Java switch
statement can accept " Constant Expressions
" and " Enum Constant Names
", as noted in section 14.11 of the Java Language Specification . 如Java 语言规范的14.11节所述 ,Java
switch
语句可以接受“ Constant Expressions
”和“ Enum Constant Names
”。
If you can provide a bit more context, a better solution to the problem may be available; 如果您可以提供更多的背景信息,则可能会找到一个更好的解决方案。 otherwise, this is as close as you get in Java:
否则,这与您在Java中获得的效果非常接近:
public class Constant
{
public static final int a=1;
public static final int b=2;
public static final int c=3;
public static void main(String[] args)
{
if(0 == args.length)
{
System.exit(-1);
}
String string=args[0];
int value=Integer.parseInt(string);
switch(value)
{
case a:
System.out.println("It's an 'a'");
break;
case b:
System.out.println("It's an 'b'");
break;
case c:
System.out.println("It's an 'c'");
break;
default:
System.out.println(String.format("It's a mystery '%s'",value));
break;
}
}
}
Since you only have 1 character I wouldn't recommend using String, instead use char. 由于您只有1个字符,因此我不建议您使用String,而建议使用char。
char string=args[0];
and then follow the answer Jan neilsen gave. 然后按照Jan Neilsen给出的答案进行操作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.