在java中,这样写switch语句有什么不妥,为什么一直提示错误

J2EE 码拜 7年前 (2017-05-05) 2117次浏览
        int aa = 1;
        switch (aa){
            case Fruit.apple.getValue():
                System.out.println("apple");
                break;
            case Fruit.banana.getValue():
                System.out.println("banana");
                break;;
            case Fruit.pare.getValue():
                System.out.println("pare");
                break;
        }

错误提示:constant expression required;

解决方案

10

//switch case中,case这里的判断条件只能是常量表达式。
 case Fruit.apple.getValue():
                System.out.println("apple");
                break;

你可以这样写:

 switch (aa){
            case 1:
                System.out.println("apple");
                break;
         case 2:
                System.out.println("banana");
                break;
 }

10

		enum Fruit {
			Apple, Orange
		}

		Fruit a = Fruit.Apple;
		switch (a) {
		case Apple:
		case Orange:
			break;
		}

CodeBye 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权 , 转载请注明在java中,这样写switch语句有什么不妥,为什么一直提示错误
喜欢 (0)
[1034331897@qq.com]
分享 (0)