简体   繁体   中英

'variable' cannot be resolved to a variable

I'm working with Eclipse and I get this error:

seats cannot be resolved to a variable

This is my program:

import java.util.*;

class Project {

    public static void printRow(char[] row) {
        for (char i : row) {
            System.out.print(i);
            System.out.print("\t");
        }
        System.out.println();
    }

    public static void method1 (char[][]seats){
        seats = new char [15][4];
        int i,j;
        char k = 'O';
        for(i=0;i<15;i++) {
            for(j=0;j<4;j++) {
                seats[i][j]=k;
            }
        }

        for(char[] row : seats) {
            printRow(row);
        }

And this is the main:

public static void main (String[]arg) {
    method1(seats);
}

I omitted the irrelevant code, Eclipse mark method1(seats) with an error, but I dont know how to fix it.

EDIT: I use a parameter for seats because I need to use in other methods.

EDIT: as you said in your comment, you need to reuse seats somewhere else in your code.

Because of that, I suggest you do the following:

private char[][] makeSeats() {
    char[][] seats = new char[15][4];
    for(int i=0; i<15; i++) {
        for(int j=0; j<4; j++) {
            seats[i][j] = 'O';
        }
    }
    return seats;
}        

public static void method1(char[][] seats) {
    for(char[] row : seats) {
        printRow(row);
    }
}

public static void printRow(char[] row) {
    for (char i : row) {
        System.out.print(i);
        System.out.print("\t");
    }
    System.out.println();
}

public static void main(String[] args) {
    char[][] seats = makeSeats();
    method1(seats);
} 

Well, because you are creating seats inside #method1() , why don't you remove the parameter from your method?

Keep in mind that parameters are necessary only when you want your method/function to behave differently based on them . If you are always doing the same thing despite any changes in your parameters, they are hardly needed.

public static void method1() {
    char[][] seats = new char[15][4];
    int i, j;
    char k = 'O';
    for(i=0; i<15; i++) {
        for(j=0; j<4; j++) {
            seats[i][j]=k;
        }
    }
    for(char[] row : seats) {
        printRow(row);
    }
}

public static void main(String[] args) {
    method1();
}

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