Type mismatch: cannot convert from Random to int [closed]
-
20-12-2019 - |
Question
How can I fill this array with random int's and avoid this type mismatch error? I have tried to cast but I wasn't very successful. Thanks
public static int[] generateRandom(int n) {
Random r = new Random(1);
r.nextInt(Integer.MAX_VALUE);
int[] ranArray = new int[n];
for (int i = 0; i < n; i++) {
ranArray[i] = r;
}
printArray(ranArray);
return ranArray;
}
Solution
You cant assign Random
type to int
for (int i = 0; i < n; i++) {
ranArray[i] = r; // Type mismatch
}
Instead do this
for (int i = 0; i < n; i++) {
ranArray[i] = r.nextInt(Integer.MAX_VALUE);;
}
OTHER TIPS
r is of type Random
whereas ranArray[i]
is integer and hence the error.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow