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.

29th Jul 2019, 1:33 AM
Dreon Wheatley Owens
Dreon Wheatley Owens - avatar
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 + " "); }
29th Jul 2019, 1:51 AM
Jake
Jake - avatar
+ 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); }
29th Jul 2019, 2:04 AM
Jake
Jake - avatar
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.
29th Jul 2019, 1:51 AM
Dreon Wheatley Owens
Dreon Wheatley Owens - avatar
0
Thank you guys for your help
29th Jul 2019, 2:02 AM
Dreon Wheatley Owens
Dreon Wheatley Owens - avatar