首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在二维数组中生成唯一的随机数

在二维数组中生成唯一的随机数
EN

Stack Overflow用户
提问于 2016-06-21 23:01:55
回答 2查看 804关注 0票数 2

我正在尝试做一个根据用户输入显示随机数的板。

例如:如果输入为3:

1 2 3

2 3 1

3 1 2

然而,我一直得到0作为我在2D数组中的值。不确定出了什么问题。感谢任何善意的帮助。

输出:

0 0 0

0 0 0

0 0 0

下面是我的代码:

代码语言:javascript
复制
Public class Mb {

    /**
     * @param args the command line arguments
     */

    public static int[][] createMatrixBoard(int size)
    {
        int[][] board = new int[size][size];
        return board;
    }

    public static void printMatrixBoard(int[][] board)
    {
        for(int i = 0; i<board.length; i++)
        {
            for(int j = 0; j<board[i].length; j++)
            {
                System.out.print(board[i][j] + " ");
            }
            System.out.println();
        }
    }

     public static void shuffleBoard(int[][] board)
    {
        Random rnd = new Random();
        int randX = 0;
        int randY = 0;

        for(int x = 0; x<board.length; x++) //no of rows
        {
            for(int y = 0; y<board[x].length; y++) //x refers to no of columns in each row
            {
                randX = rnd.nextInt(board.length);
                randY = rnd.nextInt(board.length);
                swap(board, x, y, randX, randY);
            }
        }
    }

    public static void swap(int[][] board, int x1, int y1, int x2, int y2)
    {
        int temp = board[x1][y1]; //use temp variable to store original value of one of the elemnt
        board[x1][y1] = board[x2][y2]; //swap the value position
        board[x2][y2] = temp; //swap the remaining value position
    }

    public static void main(String[] args) {
        // TODO code application logic here

        int userInput = 0;


        System.out.print("Matrix size: ");
        Scanner scn = new Scanner(System.in);
        userInput = scn.nextInt();
        while(userInput < 0 && userInput > 9)
        {
            System.out.println("Invalid matrix size. Re-enter ");

        }

        int[][] matrixBoard = new int[userInput][userInput];
        createMatrixBoard(userInput);
        shuffleBoard(matrixBoard);
        printMatrixBoard(matrixBoard);

    }

}
EN

Stack Overflow用户

发布于 2016-06-21 23:14:42

首先,为什么要交换以生成随机矩阵?您正在将您的方法交换输入作为0到2之间的整数,并且您正在使用始终为零的board[0-2][0-2]交换board[0-2][0-2]。因此,在交换之后,您将结束与零的板再次!

你所需要的是:

代码语言:javascript
复制
        for(int x = 0; x<board.length; x++) //no of rows
        {
            for(int y = 0; y<board[x].length; y++) //x refers to no of columns in each row
            {
                board[x][y] = 1 + rnd.nextInt(board.length);
            }
        }
票数 0
EN
查看全部 2 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/37948010

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档