【问题标题】:'variable' cannot be resolved to a variable“变量”无法解析为变量
【发布时间】:2015-11-21 19:48:38
【问题描述】:

我正在使用 Eclipse,但出现此错误:

席位无法解析为变量

这是我的程序:

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

这是主要的:

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

我省略了不相关的代码,Eclipse 标记method1(seats) 有错误,但我不知道如何修复它。

编辑:我为seats 使用了一个参数,因为我需要在其他方法中使用。

【问题讨论】:

  • 好吧,例如,在你的 main 中定义一个 seats 变量。
  • main 方法中seats 没有定义。它应该是数据成员吗?
  • 是错字还是您没有在 main 中定义“座位”?
  • 为什么seatsmethod1 的参数?它会立即被覆盖。

标签: java arrays methods compiler-errors


【解决方案1】:

编辑:正如您在评论中所说,您需要在代码中的其他位置重用座位。

因此,我建议您执行以下操作:

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

好吧,因为您是在#method1() 中创建seats,为什么不从您的方法中删除参数?

请记住,只有当您希望您的方法/函数根据它们表现出不同的行为时,才需要使用参数。如果您在参数发生任何变化的情况下总是做同样的事情,那么几乎不需要它们。

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

【讨论】:

  • 我需要在其他方法中使用变量'seats',这就是我使用参数的原因,谢谢你的回答btw
  • 知道了。查看您的原始代码,我认为没有必要。我会做一些调整。
猜你喜欢
  • 2011-11-27
  • 2012-04-14
  • 2021-11-20
  • 2021-12-21
  • 2012-02-29
  • 2020-12-07
  • 2019-04-13
  • 1970-01-01
相关资源
最近更新 更多