Reputation: 149
Why doesn't my code switch at b.Equal recognize "displayValue". All the other switches recognize display. Is it because it's a switch in a switch? Please let me know.
package 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. */
// Here's display
public EditText display;
double total1=0.0;
double total2=0.0;
char theOperator;
public String buttonText;
public Button ButtonAdd, ButtonEqual, ButtonMultiply, ButtonDivide;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// display
display= (EditText) findViewById(R.id.editText1);
}
public void getOperator(String btnText){
theOperator = btnText.charAt(0);
String display1= display.getText().toString();
double displayValue= Double.parseDouble(display1);
total1+=displayValue;
display.setText("");
}
// All the switches recognize and use display... except for Equals
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:
buttonText="+";
ButtonAdd= (Button)findViewById(R.id.bAdd);
ButtonAdd.setText(buttonText);
getOperator(buttonText);
break;
case R.id.bEqual:
switch (theOperator){
case '+':
//Error right here. This switch doesn't recognize displayValue,
// but the other switches recognize display. Why?
total2= total1 + displayValue;
}
}
}
}
Upvotes: 0
Views: 282
Reputation: 791
displayValue is out of scope for the method onClick. Change displayValue as a global variable..
Upvotes: 0
Reputation: 15389
This has got nothing to do with switch being inside another switch. The fact is that within the onClick() method, no such variable as displayValue even exists. The other switches recognize display, because display is a member variable of the class. They would not be able to recognize displayValue either, because displayValue is not a member variable of the class. In fact, the switch inside the switch would also be able to recognize display.
I think you are confusing "display" with "displayValue". They are different variables.
Upvotes: 4