我有我在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 } }
有趣的是,列出的两个答案都忽略了发问者正在使用静态方法的事实。因此,除非类类或成员变量也被声明为静态或静态引用,否则该方法将无法访问任何类或成员变量。这个例子:
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(); } }