简体   繁体   English

“变量”无法解析为变量

[英]'variable' cannot be resolved to a variable

I'm working with Eclipse and I get this error:我正在使用 Eclipse,但出现此错误:

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.我省略了不相关的代码,Eclipse 标记method1(seats)有错误,但我不知道如何修复它。

EDIT: I use a parameter for seats because I need to use in other methods.编辑:我使用seats参数是因为我需要在其他方法中使用。

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?好吧,因为您正在#method1()内创建seats ,为什么不从您的方法中删除参数?

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();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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