java - 在二维数组中生成随机数

标签 java arrays string

我试图让我的程序打印 1000-9999 之间的随机数,但我不断收到 String.Format 错误。

例如,如果我的程序运行,它将打印如下内容:

7996   2799   2006   2419   1147

7661   5383   8428   6487   3961

2799   8789   6948   8584   8634

7462   5051   4942   5378   1028

9978   1533   7657   4240   7894

6183   6277   9629   2996   8240

8985   9712   3922   2589   5323

8152   4612   6563   9460   3045

代码

import static java.lang.System.*;

public class SuperRandGame{
    public static void main(String args[]){
        new Environment();
}}


class Environment
{
    private int[][] table;

    Environment()
    {
        populate();
        output();
    }

    public void populate()
    {
        table = new int[8][5];

        for(int r=0;r<table.length;r++)
        {
            for(int c=0;c<table[0].length;c++)
            table[r][c]= String.format("%2d",(int)(Math.random()*8999+1000) + "  ");
        }

    }

    public void output()
    {
        out.println();
        for(int r=0;r<table.length;r++)
        {
            for(int c=0;c<table[0].length;c++)
            out.print(String.format("%2d",table[r][c]) + "  ");
            out.println();
        }
        out.println();
        out.println();
    }
}

最佳答案

String.format() 方法返回 String 类型。因此,您不能在 int[][] 数组中存储 String 类型。

关于java - 在二维数组中生成随机数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28310834/

相关文章:

java - 计算数组的元素

c# - 使用linq C#从另一个数组中的数组中查找和计数

c# - 递归方法中的 StackOverflow 异常

python - Pandas 字符串按字符转换为整数

java - 尝试检索多个 JDBC 结果

java - Elasticsearch "StatusLogger Log4j2 could not find a logging implementation. Please add log4j-core to the classpath."

java - Hibernate 数据库名称更改给出 MySQLSyntaxErrorException : Table doesn't exist

php - undefined index 行为

c中的字符数组消隐

java - 对除最后 2 行之外的 JTable 进行排序