过去几天,我一直在使用Android计算器。我已经到达了equals按钮,这是代码的最后一部分。但是,这是因为我的if语句出于某种原因未初始化theOperator。有什么帮助吗?
[码]
包rechee.cool;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class HelloAndroidActivity extends Activity {
/** Called when the activity is first created. */
public EditText display;
double counter1=0;
double counter2=0;
String display1= display.getText().toString();
String sub = "-";
String divide = "/";
String mult = "*";
//Just have two buttons so far, I'm going to have like 10 more
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Associate the button variable with the xml reference
display= (EditText) findViewById(R.id.editText1);}
//When button is clicked, display the text. How do I do this for the rest of my variables?
public void onClick(View v) {
switch(v.getId()){
case R.id.bOne:
display.append("1");
break;
case R.id.bTwo:
display.append("2");
break;
case R.id.bThree:
display.append("3");
break;
case R.id.bFour:
display.append("4");
break;
case R.id.bFive:
display.append("5");
break;
case R.id.bSix:
display.append("6");
break;
case R.id.bSeven:
display.append("7");
break;
case R.id.bEight:
display.append("8");
break;
case R.id.bNine:
display.append("9");
break;
case R.id.bZero:
display.append("0");
break;
case R.id.bPoint:
display.append(".");
break;
case R.id.bClear:
display.setText("");
break;
case R.id.bAdd:
double displayValue= Double.parseDouble(display1);
counter1+= displayValue;
display.setText("");
String theOperator= new String("+");
break;
case R.id.bEqual:
//display.setText(Double.toString(counter2));
//counter1 = 0;
// Tried using a switch for theOperator, but 1.6 doesn't allow string switch. So I'm going to use if else statements instead.
if(theOperator=="+"){
}
}
//case "+":
//break;
}
}
[/码]
最佳答案
这是因为仅在theOperator
范围内定义case R.id.bAdd
,而case R.id.bEqual
块看不到它。您可以通过在整个开关块之外或作为整个类的字段定义变量theOperator
来解决问题。