在正确的范围内创建对象

14ifxucb  于 2021-07-03  发布在  Java
关注(0)|答案(1)|浏览(261)

因为我在a类中的一个方法中创建对象,所以当我需要在另一个方法(a类中)中使用对象的方法时,它超出了范围。我之所以要在方法中创建对象,是因为创建的对象数量取决于用户输入。
有什么方法可以使用方法之外的对象吗?

public class A {
    //I was thinking I could write something here to change the scope?
    // Like: public B objekt

    public static ArrayList input(){
        input0 = reader.nextInt();

        for(int i=0; i<input0; i++){
            //user inputs: input1 & and input2
            B object = new B(input1, input2);
            list.add(objekt)
        }

        return list
    }

    public static void doSomething(ArrayList list){
        //Because the objekt is out of scope. I cannot call the method.
        list.get(index).get_input1();
    }

    public static void main(String[] args) {
        list = A.input()
        A.doSomething(list);
    }
}

public class B {
    public int input1;
    public int input2;

    public B(int input1, int input2){
        this.input1 = input1;
        this.input2 = input2;
     }

     public int get_input1(){
         return input1;
     }
}
dfty9e19

dfty9e191#

我假设您的列表定义为:

Arraylist List = new ArrayList();

您遇到的问题与您创建 B 物体。
相反,列表包含类型为 Object ,所以你不能打电话 get_input1()Object .
如果将列表的定义更改为:

List<B> list = new ArrayList<>();

... 以及您的方法签名:

public static List<B> input() {

... 那你就可以打电话了 get_input1() 在列表中的对象上。
当然,为了使代码能够编译,您需要修复代码中的其他次要编译问题。

相关问题