I need to insert randomly generated numbers into an array
I have looked through questions with similar words or intentions, but could not find one that would help me.
I created an array using user input, I need to generate numbers between 100 and 10000 and insert them into the array. I created an array, it shows as filled with zeros and I generated random numbers, but I cannot insert the randomly generated numbers into the array.
Here is my code so far.
import java.util.*;
public class Print2DArray {
public static void main(String[] args) {
System.out.println();
Scanner userInput = new Scanner(System.in);
System.out.println("Enter the number of rows");
int rows = userInput.nextInt();
System.out.println("Enter the number of columns");
int columns = userInput.nextInt();
int[][] array = new int[rows][columns];
for (int a = 0; a < rows; a++)
for (int b = 0; b < columns; b++)
array[a][b] = 0;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
System.out.print(array[i][j]);
{
Random r = new Random();
int rand = r.nextInt(10000 - 100) + 100;
}
}
System.out.println();
}
}
}
+3
source to share
4 answers
import java.util.Random;
import java.util.Scanner;
public class QuickTester {
public static void main(String[] args) {
Scanner userInput = new Scanner(System.in);
System.out.print("Enter the number of rows: ");
int rows = userInput.nextInt();
System.out.print("Enter the number of columns: ");
int columns = userInput.nextInt();
// Create the Random instance once here!
Random rand = new Random();
int[][] array = new int[rows][columns];
for (int a = 0; a < rows; a++)
for (int b = 0; b < columns; b++)
array[a][b] = rand.nextInt(10000 - 100) + 100;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
System.out.print(array[i][j] + " ");
}
System.out.println();
}
}
}
Input / Output:
Enter the number of rows: 3
Enter the number of columns: 2
574 5286
1550 5259
8343 4877
Note:
- Create Random only once, not every iteration of the double for loop
- If you want 100 to 10000 (inclusive) it should be
nextInt(10000-100+1) + 100
- Random # nextInt (int n) gives you [0, 9990) or [0, 9989], so the largest value you get from your expression is 9999, not 10000
+4
source to share
You need 3 things,
-
Assign a random value to an array.
-
Use only one nested
for loop
. -
Don't initialize
Random r
inside a loop.
Try the following:
int[][] array = new int[rows][columns];
Random r = new Random();
for (int a = 0; a < rows; a++)
for (int b = 0; b < columns; b++) {
array[a][b] = r.nextInt(10000 - 100) + 100;
System.out.print(array[a][b]);
}
System.out.println();
}
+1
source to share