【发布时间】:2018-02-13 03:39:13
【问题描述】:
因为我在 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;
}
}
【问题讨论】:
-
将
ArrayList更改为ArrayList<B>。 -
只需创建一个静态类字段,您就可以从任何方法访问它。
-
list在哪里定义?我们可以看到它在哪里使用,但您没有显示它是在哪里定义或构造的。另外,请显示可编译的代码,或仅针对您所询问的问题破坏编译器。