简体   繁体   中英

“Column” cannot be resolved to a variable

i am trying some of the practice New Boston videos and can't get this to work! I am very new to java, this is my first class. I have an assignment to do a 2d array and I can't figure out how to get it to display on the screen. This practice is from Thenewboston's Java tutorials, video # 34 and it works for him!

public class inventory {
public static void main (String[] args) {
    int firstarray[][]= {{8,9,10,11},{12,13,14,15}};
    int secondarray[][]={{30,31,32,33},{43},{4,5,6}};

    System.out.println("This is the first array");              
    display(firstarray);
    System.out.println("This is the second array");
    display(secondarray);
    }


public static void display (int x[][])
{
    for(int row=0;row<x.length;row++)
    {
        for(int column=0;column<x.length;column++);
            System.out.print(x[row][column]+"\t");
        }

     { 

    System.out.println();
     }

} }

You've put a ; after the for loop, negating what you thought was its body. Get rid of

for(int column=0;column<x.length;column++); // <--- this ; 

In this situation, the body of the for loop, where column variable is declared and has scope, is everything after the ) and before the ; . In other words, nothing. You actually need to replace the ; with a { .


Correct indentation would go a long way in helping you write syntactically correct code.

You have semicolon at the end of for cycle and not good formating. There are also two brackets, which are absolutely useless :). The right code can look like this :

public static void display(int x[][]) {
    for (int row = 0; row < x.length; row++) {
        for (int column = 0; column < x.length; column++) {
            System.out.print(x[row][column] + "\t");
        }
        System.out.println();
    }
}

Still the display function is not correct, it fails at the end, because the difference of length of rows and columns.

If you want to make this functional, at the second for cycle, you should consider the length of the actual ROW, not how many rows (which is x.length ).

You only need change column < x.length to column < x[row].length

So the working code is this :

public static void display(int x[][]) {
    for (int row = 0; row < x.length; row++) {
        for (int column = 0; column < x[row].length; column++) {
            System.out.print(x[row][column] + "\t");
        }
        System.out.println();
    }
}

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