[英]How can i access an object from another method in java?
我有在 create() 方法中創建的對象編號列表,我想訪問它以便我可以在 question() 方法中使用它。
有沒有其他方法可以做到這一點,我可能錯過了? 我搞砸了什么嗎? 如果沒有,我應該如何做到這一點以獲得與下面相同的功能?
private static void create() {
Scanner input = new Scanner(System.in);
int length,offset;
System.out.print("Input the size of the numbers : ");
length = input.nextInt();
System.out.print("Input the Offset : ");
offset = input.nextInt();
NumberList numberlist= new NumberList(length, offset);
}
private static void question(){
Scanner input = new Scanner(System.in);
System.out.print("Please enter a command or type ?: ");
String c = input.nextLine();
if (c.equals("a")){
create();
}else if(c.equals("b")){
numberlist.flip(); \\ error
}else if(c.equals("c")){
numberlist.shuffle(); \\ error
}else if(c.equals("d")){
numberlist.printInfo(); \\ error
}
}
您必須將其設為類變量。 不是在 create() 函數中定義和初始化它,而是在類中定義它並在 create() 函數中初始化它。
public class SomeClass {
NumberList numberlist; // Definition
....
然后在你的 create() 函數中說:
numberlist= new NumberList(length, offset); // Initialization
雖然有趣,但列出的兩個答案都忽略了提問者使用靜態方法的事實。 因此,任何類或成員變量都不能被方法訪問,除非它們也被聲明為靜態或靜態引用。 這個例子:
public class MyClass {
public static String xThing;
private static void makeThing() {
String thing = "thing";
xThing = thing;
System.out.println(thing);
}
private static void makeOtherThing() {
String otherThing = "otherThing";
System.out.println(otherThing);
System.out.println(xThing);
}
public static void main(String args[]) {
makeThing();
makeOtherThing();
}
}
會起作用,但是,如果它更像這樣會更好......
public class MyClass {
private String xThing;
public void makeThing() {
String thing = "thing";
xThing = thing;
System.out.println(thing);
}
public void makeOtherThing() {
String otherThing = "otherThing";
System.out.println(otherThing);
System.out.println(xThing);
}
public static void main(String args[]) {
MyClass myObject = new MyClass();
myObject.makeThing();
myObject.makeOtherThing();
}
}
在您的方法之外聲明numberList
如下所示:
NumberList numberList;
然后在create()
內部使用它來初始化它:
numberList = new NumberList(length, offset);
這意味着你可以在這個類中的任何方法來訪問它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.