java – 我需要将随机生成的数字插入到数组中
发布时间:2020-12-15 04:28:24 所属栏目:Java 来源:网络整理
导读:我用相似的词语或意图仔细查看了这些问题,但似乎找不到能帮助我的问题. 我使用用户输入创建了一个数组,我需要生成100到10000之间的数字并将其插入到数组中.我创建了数组,它显示为填充零,并且我生成了随机数,但我似乎无法将随机生成的数字插入到数组中. 到目
|
我用相似的词语或意图仔细查看了这些问题,但似乎找不到能帮助我的问题.
我使用用户输入创建了一个数组,我需要生成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 注意: >只创建一次Random,而不是double for循环的每次迭代 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
