0
What's wrong with my code?
import java.util.Random; public class RandomInt { public static void main(String[] args) { createRandomIntArray(10); } public static void createRandomIntArray(int n) { Random rand = new Random(); int randnum = rand.nextInt(101); int arr [] = new int[n]; for(int counter = 0; counter < arr.length; counter ++) { arr[counter] = randnum; } System.out.println("The array is " + arr); } } //When I run it I get a mix of random symbols.
6 Respostas
+ 1
The foreach loop is great for iterating through arrays!
System.out.print("The array is: ");
for(int i : arr) {
System.out.print(i + " ");
}
+ 1
If your intention is not having all the same numbers in each element, your issue is the fact that your randnum variable is only randomized once, thus it will have the same value throughout your code. You would need to re-assign that variable within the for loop so the number will change after each iteration. This is one way you could do that:
int max = 101;
for(int c = 0; c < arr.length; c++) {
arr[c] = rand.nextInt(max);
}
0
import java.util.Random;
public class RandomInt {
public static void main(String[] args) {
createRandomIntArray(10);
}
public static void createRandomIntArray(int n) {
Random rand = new Random();
int randnum = rand.nextInt(101);
int arr [] = new int[n];
for(int counter = 0; counter < arr.length; counter ++) {
arr[counter] = randnum;
}
for(int counter = 0; counter < arr.length; counter++) {
System.out.println("The array is " + arr[counter]);
}
}
}
//Now all the numbers are the same in each element.
0
Thank you guys for your help