Home > Back-end >  how do I fix incompatible types: possible lossy conversion from double to int?
how do I fix incompatible types: possible lossy conversion from double to int?

Time:11-13

incompatible types: possible lossy conversion from double to int BonusAttackSpeed = scan.nextDouble(); ^ 1 error

the variable was correct but it does not work solution

CodePudding user response:

Well, your variable is of type int, which can store whole numbers only, from -2^31 to 2^31-1 (from some - 2 billion to 2 billion give or take). nextDouble() reach a double, which is a data type that stores fractional numbers. It's not perfect either, it rounds in weird ways (computers aren't magic, with just 64 bits, they can't store the infinite amount of numbers between 0 and 1, let alone the some -1e300 to 1e300 it covers).

If your intent is to actually read whole numbers, call .nextInt(). If your intent is to read a fractional number, make it double bonusAttackSpeed = scan.nextDouble();. And be aware of that rounding thing.

CodePudding user response:

If you don't care about losing any fractional component of the scanned value, you can just cast the result to an int, like this:

int BonusAttackSpeed = (int)(scan.nextDouble());

Do you want your users (or values in data files if you're reading from a file) to be able to enter fractional parts of numbers (like the .5 in 10.5, for example) that you're then going to throw away? If not, then the cleanest solution would be to replace scan.nextDouble() with scan.nextInt(), like this:

int BonusAttackSpeed = scan.nextInt();

The other option would be to define BonusAttackSpeed to be a double:

double BonusAttackSpeed = scan.nextDouble();
  •  Tags:  
  • java
  • Related