In android studio, the variable "output" in my if/else statement shows up as gray(never used) and then on the last line when I try to use it, I get an error saying "cannot resolve symbol output".
Code:
public void calculate(View view) {
EditText userInput = (EditText) findViewById(R.id.user_input);
String numString = userInput.getText().toString();
double num = new Double(numString).doubleValue();
CheckBox ozCheckBox = (CheckBox)findViewById(R.id.oz);
boolean ozInput = ozCheckBox.isChecked();
CheckBox gCheckBox = (CheckBox)findViewById(R.id.g);
boolean gInput = gCheckBox.isChecked();
if(ozInput == true) {
double output = num*28.3495;
} else {
double output = num;
}
TextView textView = (TextView)findViewById( R.id.output_textview );
textView.setText( String.valueOf( output ) );
}
You're declaring the variables inside the blocks. Any local variable is out of scope outside the block in which it's declared. That's why those variables are greyed out - they aren't used anywhere, because the blocks in which they're declared end immediately after the declaration.
In this case, it would be simpler to use the conditional operator:
double output = ozInput ? num * 28.3495 : num;
That replaces your whole if
/else
statement, and declares the variable in a scope where it can be used in your setText
call.
See more on this question at Stackoverflow