猿问

如何随机化一个字符的值?

所以,我的问题是,我有一个二维字符数组。我想遍历每个元素,并随机为它们分配一个值。到目前为止,这是我的代码:


private char [][] generateTable(int rows, int columns){

        char [][] table = new char [rows][columns];

        return table;

    }


private void tableFiller(char [][] table){

        for (char[] row : table) {

            for (char character : row) {

                randomize(column);

            }

        }

    }


ublic static void randomize(char character){

        Random random = new Random();


        if (random.nextInt(100) < 50){

            character = '.';

        } else {

            character = '*';

        }

    }

现在,随机生成器方法不起作用,无法弄清楚原因。IDEA 建议我从未使用分配给字符的值,但这无济于事。我怎样才能使这种方法起作用?


当年话下
浏览 186回答 3
3回答

郎朗坤

这是问题所在:&nbsp;void randomize您的 randomize 方法返回 void,但它应该返回一个字符。然后,应该在调用函数的地方使用该字符,方法是将其分配给相关的数组索引。我建议您基于数组索引进行循环以使分配更容易。例如,而不是:for (char character : row)你会写:for (int i=0; i<row.length; i++)

白板的微信

因为char不是参考。为了让它工作,你应该改变你的 randomize 方法:public static char randomize(){&nbsp; &nbsp; Random random = new Random();&nbsp; &nbsp; char character;&nbsp; &nbsp; if (random.nextInt(100) < 50){&nbsp; &nbsp; &nbsp; &nbsp; character = '.';&nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; character = '*';&nbsp; &nbsp; }&nbsp; &nbsp; return character;}并按如下方式调用它:character = randomize();

米脂

您需要使用值来设置字符对象 character = randomize(column);private void tableFiller(char [][] table){&nbsp; &nbsp; for (char[] row : table) {&nbsp; &nbsp; &nbsp; &nbsp; for (char character : row) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;character = randomize(column);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }}或者随机化(字符);private void tableFiller(char [][] table){&nbsp; &nbsp; for (char[] row : table) {&nbsp; &nbsp; &nbsp; &nbsp; for (char character : row) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;randomize(character);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }}
随时随地看视频慕课网APP

相关分类

Java
我要回答