这是我的代码:
import java.util.Scanner;
import java.util.Arrays;
public class Fire {
public static Integer seed;
public static Integer width;
public static Integer height;
public static void main(String[] args) {
if (args.length != 3) {
System.out.println("Usage: java Firebot <seed> <width> <height>");
return;
}
try {
width = Integer.parseInt(args[1]);
height = Integer.parseInt(args[2]);
} catch (Exception e) {
System.out.println("Usage: java Firebot <seed> <width> <height>");
return;
}
Scanner keyboard = new Scanner (System.in);
Integer day = 1;
String wind = "none";
double damage = 0.00;
Integer pollution = 0;
Integer seed = Integer.parseInt(args[0]);
Integer width = Integer.parseInt(args[1]);
Integer height = Integer.parseInt(args[2]);
int [][] SimulationArray = new int[width][height];
for (int i=0; i<width; i++) {
for (int j=0; j<height; j++) {
Integer DoubleHeight = (int) Math.round(Math.random() * 10);
if (DoubleHeight == 10) {
SimulationArray[i][j] = 0;
}
else if (DoubleHeight > 2) {
SimulationArray[i][j] = DoubleHeight;
}
else {
SimulationArray[i][j] = 0;
}
}
}
for (int i=0; i<width; i++) {
for (int j=0; j<height; j++) {
if (SimulationArray[i][j] == 0) {
System.out.print(" ");
}
else {
System.out.print(Arrays.toString(SimulationArray[i]));
System.out.print(" ");
}
}
System.out.println();
}
System.out.print("\n");
}
}
我正在尝试打印一个基于随机数及其值建模的二维数组。
目前我的代码在控制台中打印如下。
[user@sahara ~]$ java Fire 4 5 4
[3, 8, 9, 3] [3, 8, 9, 3] [3, 8, 9, 3] [3, 8, 9, 3]
[6, 4, 0, 9] [6, 4, 0, 9] [6, 4, 0, 9]
[5, 0, 3, 5] [5, 0, 3, 5] [5, 0, 3, 5]
[0, 8, 6, 0] [0, 8, 6, 0]
[0, 8, 8, 6] [0, 8, 8, 6] [0, 8, 8, 6]
实际上我想要打印的是这样的
[user@sahara ~]$ java Fire 4 5 4
4 5 2 3 4
2 3 4 4 5
4 5 2 3 4
2 3 4 4 5
3 4 7 8 2
没有 [] 和单个整数。我觉得这就是我的代码应该做的(不包括整数为 0 或 10 时应打印空格的位)。 谁能告诉我为什么它会像这样打印 [0, 8, 8, 6]?
我已经尝试过了,
System.out.print(Arrays.toString(SimulationArray[i][j]));
使用上面的方法时出现错误。因为我怀疑我正在打印子数组而不是打印单个值,但我不明白为什么或如何解决这个问题。
任何帮助表示赞赏。谢谢。
最佳答案
要打印二维数组,您可以使用嵌套的 for-each 循环,如下所示:
for (int[] x : SimulationArray) {
for (int y : x) {
System.out.print(y + " ");
}
System.out.println();
}
关于java - 2D Java 数组值与我的意图不相关,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46628024/