我试图让我的程序打印 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/