Question

I get this error; bad operand types for binary operator '-' All other operations work...when I leave out the subtraction via comments like // and /* */; can someone help?

This is the code by the way; the exception is on the subtraction line.

public class Calculator {

/*
 *use 'javac Calculator.java' to compile; 
 *use 'jar cvf Calculator.jar Calculator.class' for jar;
 *use 'java Calculator' to run;
 */
public static void main(String []args) {

String NewName

Scanner user_input = new Scanner( System.in );
System.out.println("Type your name please.");
NewName = user_input.next();
System.out.println("");

System.out.println("Hello " + NewName + ".");
System.out.println("I am Hunter's java calculator program.");
System.out.println("");

//mathematical input

String operator;
float cal1, cal2;

System.out.println("Type a Number...");
cal1 = user_input.nextFloat();
System.out.println("");

System.out.println("Type another Number...");
cal2 = user_input.nextFloat();
System.out.println("");

Scanner opt = new Scanner(System.in);
System.out.println("Enter an operator");
    operator = opt.next();

//operation decisions

    if (operator.equals("+")){
        System.out.println("The answer is " + cal1+cal2 + ".");
        }
    if  (operator.equals("-")){
        System.out.println("The answer is " + cal1-cal2 + ".");
        }

    if (operator.equals("/")){
        System.out.println("The answer is " + cal1/cal2 + ".");
        }
    if (operator.equals("*")){
        System.out.println("The answer is " + cal1*cal2 + ".");
        }

}
}
Was it helpful?

Solution

You need parenthesis:

System.out.println("The answer is " + (cal1-cal2) + ".");

Otherwise what you have is treated as

System.out.println(("The answer is " + cal1) - (cal2 + "."));

which is invalid since you can't subtract strings.


Why don't you have an error with the other operators? Well, * and / have higher precedences, so those are working as expected. +, on the other hand, is overloaded to concatenate strings:

System.out.println("The answer is " + cal1+cal2 + "."); // concatenates, doesn't add

For example, if call1 is 1 and call2 is 2, the result will be:

The answer is 12.

which isn't what you want. Again, this can be solved with parenthesis.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top