Search code examples
javastringdoublecalculatorvalue-of

String cannot be converted to double


I am trying to make a calculator with Java, and everything worked normally until this error popped up: imcompatible types:

String cannot be converted to double

Invalid value type 'String' for format specifier '%.0f', parameter 1

This is the script:

private void btnResultActionPerformed(java.awt.event.ActionEvent evt) {                                     
    String answer;

    second = Double.parseDouble(display.getText()); // The second number to count
    if (operation == "+") {
        answer = String.valueOf(first + second);
        result = String.format("%.0f",answer);
        display.setText(String.valueOf(result));
    } else if (operation == "-") {
        answer = String.valueOf(first - second);
        result = String.format("%.0f",answer);
        display.setText(String.valueOf(result));
    } else if (operation == "*") {
        answer = String.valueOf(first * second);
        result = String.format("%.0f",answer);
        display.setText(String.valueOf(result));
    } else if (operation == "/") {
        answer = String.valueOf(first / second);
        result = String.format("%.0f",answer);
        display.setText(String.valueOf(result));
    }

}   

Variables "first", "second" and "result" are doubles, operation is String. I did not have this error before, but after a while it started to error those so I added String.valueOf(first + second); , before it was answer = first + second; but adding valueOf fixed that. Now the problem still exists on "result = String.format("%.0f", answer);"


Solution

  • You'll want to make answer a double as well, since you're doing calculations. It's only at display/formatting phase where you should convert to a String.

    You should put only the calculation part inside the if (i.e. answer = first + second, with answer being a double), and afterwards convert it to a String to avoid duplicate code.

    Finally use equals() to compare Strings, so operation.equals("+") and not ==.