Android studio:错误: 需要常量表达式
将一个项目作为library,通过import Moudle导入一个新项目引用时,爆出这个错误:需要常量表达式,定位到switch。于是百度一下,解决方法为把switch case,改成if else,即:
switch (v.getId()) {
// 点击了清除按钮
case R.id.btn_clear:
clear();
break;
// 点击了取消按钮
case R.id.btn_cancel:
break;
// 点击了加、减、乘、除按钮
case R.id.btn_plus:
case R.id.btn_minus:
case R.id.btn_multiply:
case R.id.btn_divide:
operator = inputText; // 运算符
refreshText(showText + operator);
break;
// 点击了等号按钮
case R.id.btn_equal:
// 加减乘除四则运算
double calculate_result = calculateFour();
refreshOperate(String.valueOf(calculate_result));
refreshText(showText + "=" + result);
break;
// 点击了开根号按钮
case R.id.ib_sqrt:
double sqrt_result = Math.sqrt(Double.parseDouble(firstNum));
refreshOperate(String.valueOf(sqrt_result));
refreshText(showText + "√=" + result);
break;
// 点击了求倒数按钮
case R.id.btn_reciprocal:
double reciprocal_result = 1.0 / Double.parseDouble(firstNum);
refreshOperate(String.valueOf(reciprocal_result));
refreshText(showText + "/=" + result);
break;
// 点击了其他按钮,包括数字和小数点
default:
// 上次的运算结果已经出来了
if (result.length() > 0 && operator.equals("")) {
clear();
}
// 无运算符,则继续拼接第一个操作数
if (operator.equals("")) {
firstNum = firstNum + inputText;
} else {
// 有运算符,则继续拼接第二个操作数
secondNum = secondNum + inputText;
}
// 整数不需要前面的0
if (showText.equals("0") && !inputText.equals(".")) {
refreshText(inputText);
} else {
refreshText(showText + inputText);
}
break;
}
改为:文章来源:https://www.toymoban.com/news/detail-834457.html
@Override
public void onClick(View v) {
String inputText;
if(v.getId() == R.id.btn_sqrt){
inputText = "厂";
} else {
inputText = ((TextView) v).getText().toString();
}
if (v.getId() == R.id.btn_clear){
clear();
} else if (v.getId() == R.id.btn_cancel) {
} else if (v.getId() == R.id.btn_plus || v.getId() == R.id.btn_minus || v.getId() == R.id.btn_multiply || v.getId() == R.id.btn_divide) {
operator = inputText;
refreshText(showText + operator);
} else if(v.getId() == R.id.btn_equal) {
double calculate_result = calculateFour();
refreshOperate(String.valueOf(calculate_result));
refreshText(showText + "=" + result);
} else if(v.getId() == R.id.btn_sqrt) {
double sqrt_result = Math.sqrt(Double.parseDouble(firstNum));
refreshOperate(String.valueOf(sqrt_result));
refreshText(showText+"厂="+result);
} else if(v.getId() == R.id.btn_reciprocal){
double reciprocal_result = 1.0 / Double.parseDouble(firstNum);
refreshOperate(String.valueOf(reciprocal_result));
refreshText(showText+"/="+result);
} else {
if(result.length() > 0 && operator.equals("")){
clear();
}
if(operator.equals("")){
firstNum = firstNum + inputText;
} else {
secondNum = secondNum + inputText;
}
if(showText.equals("0") && !inputText.equals(".")){
refreshText(inputText);
} else {
refreshText(showText+inputText);
}
}
}
具体原因:http://tools.android.com/tips/non-constant-fields.文章来源地址https://www.toymoban.com/news/detail-834457.html
到了这里,关于Android studio:错误: 需要常量表达式的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!