Just another IT Guy - 1 month ago 11x

Java Question

I have what I think should work but Java doesn't like it.

I get this error:

`project5.java:10: error: incompatible types: possible lossy conversion from double to int`

int Low = Math.sqrt(count);

^1 error

Here is my code:

`import java.util.*`

public class project5

{

public static void main (String args[])

{

int count = 1;

while (count < 11) {

Random r = new Random();

int Low = Math.sqrt(count);

int High = count;

int Result = r.nextInt(High-Low) + Low;

System.out.println( count + "\t" + Math.sqrt(count));

count++;

}

}

}

Any suggestions?

Answer

You can just cast the result to `int`

:

```
int Low = (int) Math.sqrt(count);
```

This works fine, if you are fine with taking floor from result. If you want it rounded, then do

```
(int) Math.round(Math.sqrt(count));
```

It's safe to cast to `int`

in this particular case, as `count`

is an `int`

and `sqrt`

of it always fits in `int`

range.

Source (Stackoverflow)

Comments