Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 :)

like image 227
Fraser Price Avatar asked Dec 21 '25 05:12

Fraser Price


1 Answers

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)); 
like image 103
Lawrence Dol Avatar answered Dec 22 '25 20:12

Lawrence Dol



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!