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

i have the object numberlist that i created in create() method and i want to access it so i can use it in the question() method.

Is there a way to do this that I'm missing, or am I just messing something up? If not, how should I go about doing this to enable me to get the same functionality as below?

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

}

}

解决方案

While interesting, both of the answers listed ignored that fact that the questioner is using static methods. Thus, any class or member variable will not be accessible to the method unless they are also declared static, or referenced statically.

This example:

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();

}

}

Will work, however, it would be better if it was more like this...

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();

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值