[英]I need to insert randomly generated numbers into an array
我用相似的詞語或意圖仔細查看了這些問題,但似乎找不到能幫助我的問題。
我使用用戶輸入創建了一個數組,我需要生成100到10000之間的數字並將其插入到數組中。 我創建了數組,它顯示為填充零,並且我生成了隨機數,但我似乎無法將隨機生成的數字插入到數組中。
到目前為止,這是我的代碼。
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();
}
}
}
輸入輸出:
Enter the number of rows: 3
Enter the number of columns: 2
574 5286
1550 5259
8343 4877
注意:
nextInt(10000-100+1) + 100
array[i][j] = r.nextInt(10000 - 100) + 100;
您沒有將rand分配給數組元素。 你的第二個循環應該是
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();
}
你需要做3件事,
將隨機值分配給數組。
只使用一個嵌套for loop
。
不要在循環內初始化Random r
。
試試這個:
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();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.