简体   繁体   中英

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

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 (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. 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.

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

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

在第二个内部for循环之后,您缺少花括号

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM