如何在B类中使用A类的数组,试过了返回值

故事熊
  • 69

需求:在其他类中对数组进行:循环打印输出数组名称(字符串)。
在A类中创建数组,代码如下:

 public int[] exampleList() {
    int exampleList1 = 0;
    int exampleList2 = 1;
    int exampleList3 = 2;
    int exampleList4 = 3;
    int exampleList5 = 4;

    int allexampleList = 5;
    int[] exampleLists = new int[allexampleList]; 

    String[] songsListName = new String[5];
    songsListName[SongsList1] = "示例1";
    songsListName[SongsList2] = "示例2";
    songsListName[SongsList3] = "示例3";
    songsListName[SongsList4] = "示例4";
    songsListName[qqMusicSongsList] = "示例5";

    return exampleLists; //使用返回值让其他类调用

    }

在B类中,如何将exampleLists点击跳转到数组里的exampleLists,
即引用数组int[] exampleLists = new int[allexampleList]行,
代码如下:

class exampleThread implements Runnable { 

    int[] exampleLists = new int[]; 
    //报错Array initializer expected

    @Override
    public void run() {
        for (int i = 0; i < exampleLists[i]; i++) {
            exampleList[i] = (int) Math.random(); 
            System.out.println(exampleLists[i]); //间隔输出
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

参考链接:java 中一个类怎么调用另一个类的数组元素

回复
阅读 1.6k
3 个回答

增加构造方法,然后在main创建对象的时候将A类返回的数组传入进去。另外你for里变量书写错误,我已经更正。代码如下:

class exampleThread implements Runnable { 
    
    private int[] exampleLists;

    public exampleThread(int[] exampleLists) {
        this.exampleLists = exampleLists;
    }

    @Override
    public void run() {
        for (int i = 0; i < exampleLists[i]; i++) {
            exampleLists[i] = (int) Math.random();
            System.out.println(exampleLists[i]); //间隔输出
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

传值都不会??

https://www.runoob.com/java/j...

class exampleThread implements Runnable { 

    int[] exampleLists;
    public exampleThread(int[] exampleLists){
        this.exampleLists = exampleLists;
    }

    @Override
    public void run() {
        //...
    }
}

直接调用方法, 返回值赋值给自己的数组变量就可以

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
宣传栏