Fraser Price
Fraser Price

Reputation: 909

Can't subtract one double from another?

Im quite new to Java and programming in general, but Ive read up on it quite a bit. Im currently making my first real OOP- a calculator that can perform certain equations. However, while trying to program something that would calculate the variance of a distribution -Heres the code:

void variance() {
  System.out.println("The variance of a distribution with x values of " + a + b + "and mean" 
                + mean + "is " + a*a+b*b/2 - mean*mean); 
}

I get the error

Bad operand types for binary operator '-' First type = string Second type = double".

I had previously stated that a, b and mean were doubles and had also stated how mean is calculated. I also tried changing a*a+b*b/2 from a string to a double, but then realized that if i put any integers or doubles into where a*a+b*b/2 (e.g. 2) but i get the same error. Any help would be much appreciated :)

Upvotes: 3

Views: 1589

Answers (4)

Óscar López
Óscar López

Reputation: 236004

Surround all mathematical expressions between parenthesis, and (depending on the actual type of a, b, mean), it's better to divide by 2.0, to make sure that a floating-point division is performed.

Upvotes: 2

L. Cornelius Dol
L. Cornelius Dol

Reputation: 64026

That's because the + is overloaded in Java for string concatenation. You need to put parentheses around your math expression.

System.out.println("The variance of a distribution with x values of " + a + b + "and mean" 
 + mean + "is " + (a*a+b*b/2 - mean*mean)); 

Upvotes: 5

knownasilya
knownasilya

Reputation: 6143

You are mixing the String + operator with the Double operator.

Try this:

System.out.println( "The variance of a distribution with x values of " 
    + ( a + b ) + " and mean " 
    + mean + " is " 
    + ( ( a * a + b * b / 2 ) - ( mean * mean )) ); 

Upvotes: 0

Greg Hewgill
Greg Hewgill

Reputation: 993015

The short answer is you need to do this:

            + mean + "is " + (a*a+b*b/2 - mean*mean)); 

The longer answer is that Java evaluates your expression from left to right. So step by step, it happens something like this:

  1. mean + "is " + a*a+b*b/2 - mean*mean
  2. string + "is " + a*a+b*b/2 - mean*mean
  3. string + a*a+b*b/2 - mean*mean
  4. string - mean*mean

The compiler stops here because although you can concatenate a string and a number using + (in step 3), it doesn't make sense to subtract a number from a string. By using parentheses around the whole arithmetic expression, that will cause the arithmetic to be evaluated first, before the result is concatenated with the rest of your output string.

Upvotes: 3

Related Questions