0

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 ) );
}

2 Answers2

5

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.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
0

Your variable is used out of scope - see my comments:

boolean gInput = gCheckBox.isChecked();
if(ozInput == true) {
    //declared inside block
    double output = num*28.3495;
    //end of block - output becomes unknown      
} else {
    //declare inside block
    double output = num;
    //end of block - outpt becomes unknown
}
TextView textView = (TextView)findViewById( R.id.output_textview );
// output not known
textView.setText( String.valueOf( output ) );

The most easy way to fix would be to pre-assign else-value:

double output = num;
if(ozInput == true) {
    //reassign value
    output = num*28.3495; 
}
//name output still known
Jan
  • 13,738
  • 3
  • 30
  • 55