【问题标题】:JAVA - can't call my array methodJAVA - 无法调用我的数组方法
【发布时间】:2015-12-15 07:12:12
【问题描述】:

Eclipse 说:'chiffres 无法解析为变量',如何修复调用方法?

public class Table {

public static void main(String[] args) {


    Tableau1 table = new Tableau1();


    table.CreerTable();
    table.AfficherTable(chiffres);

}}

部分: 和 class Tableau1 with array: 来声明它

public class Tableau1 {
int [][] chiffres;
int nombre;
public void CreerTable(){

    int[][] chiffres= {{11,01,3},
                        {12,02,4},
                        {12,03,5}};
    //edited
    this.chiffres=chiffres;


}

public int[][] AfficherTable(int[][] chiffres){
    this.nombre=12;
    for(int i=0;i<2;i++){

    System.out.println("essai"+chiffres[i][1]);
    if(chiffres[i][0]==nombre){System.out.println("ma ligne ="+chiffres[i][0]+","+chiffres[i][1]+","+chiffres[i][2]);
                                };

                        }
                        return chiffres;
}

}

非常感谢

【问题讨论】:

  • 是的,它是什么,在哪里声明?
  • 抱歉我贴了两次
  • 您忘记声明变量“chiffres”了吗?我在你的主要方法中没有看到它。
  • @chris_cx 变量需要在使用前声明。你在代码中声明它的位置?
  • 那是你的完整代码吗?!我没有看到任何关于 chiffres 的声明?!是 Tableau1 中的类型吗?!还是一堂课?!

标签: java arrays methods call


【解决方案1】:

chiffers 既不是 main 方法的局部变量,也不是 Table 类的字段,这就是错误的原因。

【讨论】:

    【解决方案2】:
        table.CreerTable();
        table.AfficherTable(chiffres);
    

    通过解析 chiffres,它会在类表中搜索,因为您没有指定 chiffres 来自 Tableau1。 因此解决方案是:

        table.CreerTable();
        table.AfficherTable(table.chiffres);
    

    【讨论】:

    • this.chiffres=chiffres;
    【解决方案3】:

    这里有 3 个问题。

    问题一:

    1) AfficherTable(chiffres) 方法不需要传递参数,因为它是实例成员。

    你可以简单地调用

    table.AfficherTable();
    

    这解决了你的问题。

    在做那个问题之前没有 2

    问题 2:

    2) 你将 chifferes 删除为实例成员 int [][] chiffres;

    你正在初始化它在构造函数中

    public void CreerTable(){
    
        int[][] chiffres= {{11,01,3},
                            {12,02,4},
                            {12,03,5}};
    
    }
    

    但是,如果您仔细观察,您会再次创建新数组。那是行不通的,因为您正在创建新数组并忘记了您的实例成员。

    将您的构造函数更改为

    public void CreerTable(){
    
            chiffres= new  int[3][3] {{11,01,3},
                                {12,02,4},
                                {12,03,5}};
    
        }
    

    问题3:

    更改该构造函数后,由于您在同一个类成员中使用它,因此您不需要接收它。因此,您将方法声明更改为

    public int[][] AfficherTable(){
    

    我想你现在会没事的。

    【讨论】:

    • 谢谢,有更简单的解决方案,但我会测试你的,以备不时之需
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-04-05
    • 2016-07-31
    • 2018-06-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多