加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

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循环的每次迭代
>如果你想要100到10000(含),它需要是nextInt(10000-100 1)100
> Random#nextInt(int n)给你[0,9990]或[0,9989]所以你从表达式得到的最大值是9999,而不是10000

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读