我正在編程Android計算器。我有我的所有代碼,但使用計算器時,它總是打印「0.0」,這是我爲total1和total2設置的原始值。所以,我的假設是方法沒有看到這兩個變量。所以我假設我必須將它們設置爲靜態變量,以便我的其他代碼可以使用它們並進行更改。我可能會設置錯誤的靜態變量。但是在將total1和total2設置爲靜態變量之後,我仍然有同樣的問題。我關於爲什麼我的程序無法正常工作的其他猜測是我的displayValue變量。在我的if語句中,它表示不使用局部變量displayValue。我將不勝感激任何幫助。Android計算器代碼中的靜態變量問題?
package rechee.cool;
import android.app.Activity;
import android.os.Bundle;
import android.text.Editable;
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;
String display1;
double displayValue;
// I want to be able to use the following two variables everywhere in the code.
static double total1=0.0;
static double total2=0.0;
char theOperator;
public String buttonText;
public Button ButtonAdd, ButtonEqual, ButtonMultiply, ButtonDivide, ButtonMinus;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
display= (EditText) findViewById(R.id.editText1);
if(display.length()!=0){
String display1= display.getText().toString();
// Says local variable displayValue has not been used. May be my problem?
double displayValue= Double.parseDouble(display1);
}
}
public void getOperator(String btnText){
theOperator = btnText.charAt(0);
total1+=displayValue;
display.setText("");
}
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:
total2= 0.0;
display.setText("");
break;
case R.id.bAdd:
buttonText="+";
ButtonAdd= (Button)findViewById(R.id.bAdd);
ButtonAdd.setText(buttonText);
getOperator(buttonText);
break;
case R.id.bMinus:
buttonText="-";
ButtonMinus= (Button)findViewById(R.id.bMinus);
ButtonMinus.setText(buttonText);
getOperator(buttonText);
break;
case R.id.bMultiply:
buttonText="*";
ButtonMultiply= (Button)findViewById(R.id.bMultiply);
ButtonMultiply.setText(buttonText);
getOperator(buttonText);
break;
case R.id.bDivide:
buttonText="/";
ButtonDivide= (Button)findViewById(R.id.bDivide);
ButtonDivide.setText(buttonText);
getOperator(buttonText);
break;
case R.id.bEqual:
switch (theOperator){
case '+':
total2= total1 + displayValue;
break;
case '-':
total2= total1 - displayValue;
break;
case '*':
total2= total1 * displayValue;
break;
case '/':
total2= total1/displayValue;
break;
}
display.setText(Double.toString(total2));
total1=0.0;
break;
}
}
}
爲什麼你的onCreate重新聲明displayValue變量()方法? – JProgrammer 2012-02-28 17:27:59