Madhur Ahuja
Madhur Ahuja

Reputation: 22681

java division: Inconvertible types found: int

What's wrong with this code

int numOfPrimes=pf.FindNumPrimes(10000);
Double frequency=((Double)numOfPrimes)/10000d;

Says

inconvertible types found : int required: java.lang.Double Double frequency=((Double)numOfPrimes)/10000d;

Upvotes: 2

Views: 2199

Answers (3)

Mihai Toader
Mihai Toader

Reputation: 12243

Double is not a primitive type (like int, long, byte, etc). It's a class type. You can convert between double and Double using autoboxing but not between int and Double.

You should either declare numOfPrimes as double or do the cast to a double instead of a Double

double numOfPrimes=pf.FindNumPrimes(10000);
Double frequency=((Double)numOfPrimes)/10000d;

or

int numOfPrimes=pf.FindNumPrimes(10000);
Double frequency=((double)numOfPrimes)/10000d;

or without unnecessary casts:

double numOfPrimes = pf.FindNumPrimes(10000);
Double frequency= numOfPrimes /10000d;

or

int numOfPrimes = 10;
Double frequency = numOfPrimes /10000d;

Upvotes: 3

Bozho
Bozho

Reputation: 597096

Don't cast from primitives to wrapper types. Use lower-case double. And you don't need any casting in this case - the compiler does that automatically. The above can be simplified to:

int numOfPrimes = ...;
double frequency = numOfPrimes / 10000d;

You should almost never mix primitives with wrappers. And always prefer primitives (if possible). Use Double.valueOf(..) for conversion if you need to.

Upvotes: 4

MRalwasser
MRalwasser

Reputation: 15953

You're trying to autobox an int to a Double object, which is invalid.

Try:

int numOfPrimes=pf.FindNumPrimes(10000);

Double frequency=((double)numOfPrimes)/10000d;

Upvotes: 4

Related Questions