0

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] + "]");
        }

    }
}

5 Answers 5

2

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] + "]");
}
Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

0

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] + "]");
    }
}

Comments

0

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] + "]");
    } 
  }
}

Comments

0

after the second inner for loop you are missing braces

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.