如何从java中的另一个方法访问对象?

Llo*_*ron 6 java

我有我在create()方法中创建的对象numberlist,我想访问它,所以我可以在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
    }
}
Run Code Online (Sandbox Code Playgroud)

小智 3

虽然有趣,但列出的两个答案都忽略了提问者正在使用静态方法的事实。因此,任何类或成员变量都不能被该方法访问,除非它们也声明为静态或静态引用。这个例子:

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();
    }
}
Run Code Online (Sandbox Code Playgroud)

会工作,但是,如果它更像这样就更好了......

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();
    }
}
Run Code Online (Sandbox Code Playgroud)