I've looked through the questions with similar words or intent, but can't seem to find one that would help me.
I have created an array using user input, I need to generate numbers between 100 and 10000 and insert it into the array. I have created the array, it shows as filled with zeroes, and I have generated the random numbers, but I can't seem to insert the randomly generated numbers into the array.
Here's 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();
}
}
}
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:
nextInt(10000-100+1) + 100
array[i][j] = r.nextInt(10000 - 100) + 100;
You are not assigning rand to array element. Your 2nd for loop should be
Random r = new Random();
for(int i = 0; i<rows; i++)
{
for(int j = 0; j<columns; j++)
{
array[i][j] = r.nextInt(900) + 100;
System.out.print(array[i][j] + " ");
}
System.out.println();
}
You need 3 things to do,
Assign the random value into the array.
Use only one nested for loop
's.
Do not initialize Random r
inside the loop.
Try this:
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();
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.