我试图在Android Studio中制作自己的计算器应用程序,但是最近我得到了一个错误的语句,必须用案例标签进行预先准备。我做了两个双打(一个是第一个数字,第二个数字是第二个数字(。我有16个按钮(0-9 plus,减,分隔,乘 清晰且等于(,我在MainActivity中都有以下代码。java:
Button button1 = (Button)findViewById(R.id.button1);
对于除"等于"以外的每个按钮我都有:
//Button 1 Event Handler
button1.setOnClickListener(
//Button 1 Interface
new Button.OnClickListener(){
//Button 1 Callback Method
public void onClick(View v){
TextView output = findViewById(R.id.editText);
output.append("1");
}
}
); ``
对于" equals",我有以下代码:
buttonE.setOnClickListener(
new Button.OnClickListener(){
public void onClick(View v){
TextView output = findViewById(R.id.editText);
tempDouble2 = String.valueOf(tempDouble);{
switch (sign .equals("+")){
output.setText(tempDouble + tempDouble2);
break;
}
case (sign .equals("-")){
output.setText(tempDouble - tempDouble2);
break
}
case (sign .equals("X"));{
output.setText(tempDouble * tempDouble2);
}
case (sign .equals("/")){
if (tempDouble2 = 0){
//Cannot devide by zero
output.setText("X");
}
else {
output.setText(tempDouble / tempDouble2);
}
}
//Reset the Sign variable
sign = "";
}
}
);
});
,但我似乎无法正常工作:|有人知道吗,并且可以表明需要更改以使我的代码正常工作吗?谢谢!
如果要使用switch
语句而不是一堆if
和else if
语句,则必须像这样格式化:
switch (sign) {
case "+":
output.setText(tempDouble + tempDouble2);
break;
case "-":
output.setText(tempDouble - tempDouble2);
break
case "X":
output.setText(tempDouble * tempDouble2);
case "/":
if (tempDouble2 = 0) {
//Cannot devide by zero
output.setText("X");
} else {
output.setText(tempDouble / tempDouble2);
}
}
您可能想要break
中的CC_5。
- 您正在错误地使用开关案例。看看示例。
- 我假设您正在尝试使用
double
添加String
。那是错误的。