It is necessary to sort an array, but the compiler swears, gives an error

possible lossy conversion from double to int

What mistake do I make?

int[] mas = {9,6,3,8,5,2,7,4,1}; for (int i = 0; i < mas.length; i++) { mas[i] = Math.floor(Math.random() * 8); } for (int i = 0; i < mas.length; i++) { System.out.print(mas[i] + " "); } 

    2 answers 2

    The error is that the result of Math.floor is of type double, whereas you are trying to assign it to a variable of type int, which is a narrowing conversion and can lead to data loss, which is what the compiler says. To cure it, cast the result of Math.floor to int if the loss of the fractional part is not critical (for example, the number 8.142 will turn into 8). For example:

     mas[i] = (int)Math.floor(Math.random() * 8); 

    Or change the type of array elements from int to double

    • Thanks, helped + - maximus

    The fact is that Math.floor defined as follows.

     public static double floor(double a) ^^^^^^ 

    When you try to save a real number in an integer variable, data may be lost, and you get a warning

    You need to explicitly cast the result to an int type to store it in an integer variable.

     mas[i] = (int)Math.floor(Math.random() * 8); 
    • Thanks, helped + - maximus