Java – I need to insert randomly generated numbers into the array
•
Java
I examined these questions carefully with similar words or intentions, but it seems that I can't find any questions that can help me
I created an array using user input. I need to generate a number between 100 and 10000 and insert it into the array I created an array, which appears to be filled with zeros, and I generated random numbers, but I don't seem to be able to insert randomly generated numbers into the array
So far, this is my code
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(); } } }
Solution
import java.util.Random;
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
be careful:
>Create random only once, not every iteration of double for loop > if you want 100 to 10000 (inclusive), it needs nextint (10000-100 1) 100 > Random #nextint (int n) to give you [09990] or [09989], so the maximum value you get from the expression is 9999, not 10000
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码