我用Java创建了一个二维数组,我正在寻找一种在控制台上打印它的方法,以便我可以确认我正在制作的东西是正确的.我在网上发现了一些为我执行此任务的代码,但我对代码的特定含义有疑问.
int n = 10;
int[][] Grid = new int[n][n];
//some code dealing with populating Grid
void PrintGrid() {
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
System.out.print(Grid[i][j] + " ");
}
System.out.print("\n");
}
}
Run Code Online (Sandbox Code Playgroud)
"\n"有什么作用?我尝试在谷歌上搜索,但由于这是一小段代码,我找不到多少.
我在重新分配数组中的值时遇到了麻烦.
public static void main(String[] {
int[] arrayOfIntegers = new int[4];
arrayOfIntegers[0] = 11;
arrayOfIntegers[1] = 12;
arrayOfIntegers[2] = 13;
arrayOfIntegers[3] = 14;
arrayOfIntegers = {11,12,15,17};
}
Run Code Online (Sandbox Code Playgroud)
为什么我无法以我尝试过的方式重新分配价值观?如果我做不到,为什么我不能这样做?
有没有理由我不能在for循环之外初始化变量的起始值?当我这样做:
public static void main(String[] args) {
int userInt = 1;
int ender = 10;
for (userInt; userInt < ender; userInt++) {
System.out.println(userInt);
Run Code Online (Sandbox Code Playgroud)
我收到一个语法错误,指出userInt需要分配一个值,即使我已经为它指定了值1.当我这样做时:
public static void main(String[] args) {
int userInt;
int ender = 10;
for (userInt = 1; userInt < ender; userInt++) {
System.out.println(userInt);
Run Code Online (Sandbox Code Playgroud)
错误消失了.这是什么原因?
我期待我的代码打印一个从0到14的整数序列,但它不打印出任何东西,我不知道为什么.
public static void main(String[] args) {
int userInt;
int ender = 15;
for (userInt = 0; userInt>ender; userInt++) {
System.out.println(userInt);
}
}
Run Code Online (Sandbox Code Playgroud) 这是我GridGenerator班上的代码.目的是创建多个矩形房间,最终可以将它们连接在一起成为地图.
int xRange, yRange;
//constructor
public GridGenerator(int xInput, int yInput) {
xRange = xInput;
yRange = yInput;
}
int[][] grid = new int[yRange][xRange];
//the first number indicates the number of rows, the second number indicates the number of columns
//positions dictated with the origin at the upper-left corner and positive axes to bottom and left
void getPosition(int x, int y) {
int position = grid[y][x]; //ArrayIndexOutOfBoundsException here
System.out.println(position);
}
Run Code Online (Sandbox Code Playgroud)
这是我MapperMain班上的代码.目的是将GridGenerator实例连接到多房间地图.我现在也将它用于调试和脚手架目的.
public static void main(String[] …Run Code Online (Sandbox Code Playgroud)