java中使用switch case报错case expressions must be constant expressions

时间:2022-05-07 22:44:17

一、发现问题

private int CLICK_QUERY = 1;
private int CLICK_RESET = 2;

@Override
public void onClick(View v)
{
 int tag = (Integer) v.getTag();
 switch (tag)
 {
  case CLICK_QUERY:
   query();
  break;
  case CLICK_RESET:
   reset();
  break;
 }
}
编译时一直报错:CLICK_QUERY 和CLICK_RESET——case expressions must be constant expressions

 


二、解决问题

case后面必须跟常量,必须要常量,将上面两个变量声明为final即可。

private final int CLICK_QUERY = 1;
private final int CLICK_RESET = 2;

本文出自 “IT徐胖子的专栏” 博客,请务必保留此出处http://woshixy.blog.51cto.com/5637578/1095169