Reputation: 328
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
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] + "]");
}
}
}
Upvotes: 0
Views: 90
Reputation: 372
You forgot the braces for the inner for loop:
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] + "]");
it will not know which j
we are talking about.
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] + "]");
}
}
Upvotes: 0
Reputation: 13169
Your second for
loop does not use curly braces, so it only includes the first statement immediately following the for
statement. So only the line
array[i][j]= spacesymbol;
is actually in scope for the variable j
. The line after that is outside of the for
loop, so the variable j
no longer exists. 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.
Upvotes: 2
Reputation: 18964
You're missing the braces after your second for-loop.
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] + "]");
}
}
}
Upvotes: 0
Reputation: 2070
You forgot braces for the second for loop, change it to:
for (int j=0; j<ArraySize; j++) {
array[i][j]= spacesymbol;
System.out.println("[" + array[i][j] + "]");
}
Upvotes: 2