-3

I am attempting to write a program that pick s a random value that the user inputs and I am getting the error - possible lossy conversion from double to int. Here is my code. Any help is appreciated.

public class Driver
{
public static void main(String [] args)throws IOException{
    int random;
    int options;
    Scanner input = new Scanner(System.in);
    int randy;
    System.out.print("Please enter the number of options you would like to use: ");
    String [] choices = new String [input.nextInt()];
    int min = 1;
    int max = choices.length;
    random = (Math.random() * ((max - min) + 1)) + min;
    for(int i = 0; i < choices.length; i++){
        System.out.print("Enter option " + (i+1) + ": ");
        choices[i] = input.next();
    }
     System.out.print("The random option chosen is: " + choices[random]);
}
}
  • 2
    [`Math.random()`](https://docs.oracle.com/javase/7/docs/api/java/lang/Math.html#random()) returns a double. – 001 Apr 18 '18 at 02:27
  • If you use `java.util.Randon` it has `nextInt` https://docs.oracle.com/javase/7/docs/api/java/util/Random.html#nextInt() – Scary Wombat Apr 18 '18 at 02:33
  • I have to ask: did you even type the error message into your search engine of choice before posting here? – John3136 Apr 18 '18 at 02:33

3 Answers3

0

The reason you are getting that error is because Math.random() returns a double. Therefore the line

(Math.random() * ((max - min) + 1)) + min;

would try to assign a double to random which is an int. The compiler does not like seeing this, so you won't get passed through it. There is a solution to this. You could cast it to an int, giving you

(int)((Math.random() * ((max - min) + 1)) + min);

This would just round the value down. Note that doing this will never get you the value of max, so you don't need to worry about an IndexOutOfBoundsException.

bluewind03
  • 121
  • 4
0

As a side note: When you try to assign a data type of a larger value to a smaller data type, the value could become truncated. This is a type safety issue.

-1

since Math.random() returns a doube, cast random or Math.random() to int:

...
random = (int) ((Math.random() * ((max - min) + 1)) + min);
...
Cuttlefish
  • 99
  • 2
  • 4