[英]two-dimensional array java
Can't understand what I am doing wrong :( I want to fill my array with spaces. But receive a mistake Exception in thread "main" java.lang.Error: Unresolved compilation problem: j cannot be resolved to a variable 无法理解我在做什么错了:(我想用空格填充我的数组。但是收到错误“线程” main“ java.lang.Error中的异常:未解决的编译问题:j无法解析为变量
at Field.space(Field.java:11)
at Main.main(Main.java:6)
This is my simple code: 这是我的简单代码:
public class Main {
public static void main (String[] args){
Field field = new Field();
field.space();
}
}
public class Field {
private static final int ArraySize = 3;
private char spacesymbol = ' ';
private char[][] array = new char [ArraySize][ArraySize];
public void space() {
for (int i=0; i<ArraySize; i++){
for (int j=0; j<ArraySize; j++)
array[i][j]= spacesymbol;
System.out.println("[" + array[i][j] + "]");
}
}
}
You forgot braces for the second for loop, change it to: 您忘记了第二个for循环的花括号,将其更改为:
for (int j=0; j<ArraySize; j++) {
array[i][j]= spacesymbol;
System.out.println("[" + array[i][j] + "]");
}
Your second for
loop does not use curly braces, so it only includes the first statement immediately following the for
statement. 您的第二个
for
循环不使用花括号,因此它仅包括紧随for
语句之后的第一个语句。 So only the line 所以只有线
array[i][j]= spacesymbol;
is actually in scope for the variable j
. 实际上在变量
j
范围内。 The line after that is outside of the for
loop, so the variable j
no longer exists. 此后的行在
for
循环之外,因此变量j
不再存在。 Change your code to this to fix this error: 更改您的代码以解决此错误:
for (int i=0; i<ArraySize; i++){
for (int j=0; j<ArraySize; j++) {
array[i][j]= spacesymbol;
System.out.println("[" + array[i][j] + "]");
}
}
For this reason, I always recommend using the curly braces for any for
block. 因此,我总是建议对任何
for
块使用花括号。
You're missing the braces after your second for-loop. 在第二个for循环之后,您丢失了花括号。
public void space() {
for (int i=0; i<ArraySize; i++){
for (int j=0; j<ArraySize; j++) {
array[i][j]= spacesymbol;
System.out.println("[" + array[i][j] + "]");
}
}
}
You forgot the braces for the inner for loop: 您忘记了内部for循环的花括号:
for (int i=0; i<ArraySize; i++){
for (int j=0; j<ArraySize; j++)
array[i][j]= spacesymbol;
System.out.println("[" + array[i][j] + "]"); // 'j' who?
}
Without them it will only execute the next line after it ( array[i][j]= spacesymbol;
), and when we do the System.out.println("[" + array[i][j] + "]");
没有它们,它将仅在它之后执行下一行(
array[i][j]= spacesymbol;
),并且当我们执行System.out.println("[" + array[i][j] + "]");
it will not know which j
we are talking about. 它不会知道我们在谈论哪个
j
。
So the new code will look like this: 因此,新代码将如下所示:
for (int i=0; i<ArraySize; i++){
for (int j=0; j<ArraySize; j++){
array[i][j]= spacesymbol;
System.out.println("[" + array[i][j] + "]");
}
}
在第二个内部for循环之后,您缺少花括号
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.