Java解决No enclosing instance of type PrintListFromTailToHead is accessible问题的两种方案
程序员文章站
2024-03-13 10:00:21
今天在编译java程序时遇到如下问题:
no enclosing instance of type printlistfromtailtohead is accessib...
今天在编译java程序时遇到如下问题:
no enclosing instance of type printlistfromtailtohead is accessible. must qualify the allocation with an enclosing instance
of type printlistfromtailtohead (e.g. x.new a() where x is an instance of printlistfromtailtohead).
源代码为:
public class printlistfromtailtohead { public static void main(string[] args) { listnode one = new listnode(1); listnode two = new listnode(2); listnode three = new listnode(3); one.next = two; two.next = three; arraylist<integer> result = printlistfromtailtohead(one); system.out.println("结果是:" + result); } class listnode { public int val; public listnode next; public listnode() { } public listnode(int val) { this.val = val; } } public static arraylist<integer> printlistfromtailtohead(listnode listnode) { stack<integer> stack = new stack<integer>(); while (listnode != null) { stack.push(listnode.val); listnode = listnode.next; } arraylist<integer> arraylist = new arraylist<integer>(); while (!stack.isempty()) { arraylist.add(stack.pop()); } return arraylist; } }
问题解释:
代码中,我的listnode类是定义在printlistfromtailtohead类中的内部类。listnode内部类是动态的内部类,而我的main方法是static静态的。
就好比静态的方法不能调用动态的方法一样。
有两种解决办法:
第一种:
将内部类listnode定义成静态static的类。
第二种:
将内部类listnode在printlistfromtailtohead类外边定义。
两种解决方法:
第一种:
public class printlistfromtailtohead { public static void main(string[] args) { listnode one = new listnode(1); listnode two = new listnode(2); listnode three = new listnode(3); one.next = two; two.next = three; arraylist<integer> result = printlistfromtailtohead(one); system.out.println("结果是:" + result); } static class listnode { public int val; public listnode next; public listnode() { } public listnode(int val) { this.val = val; } }
第二种:
public class printlistfromtailtohead { public static void main(string[] args) { listnode one = new listnode(1); listnode two = new listnode(2); listnode three = new listnode(3); one.next = two; two.next = three; } public static arraylist<integer> printlistfromtailtohead(listnode listnode) { stack<integer> stack = new stack<integer>(); while (listnode != null) { stack.push(listnode.val); listnode = listnode.next; } arraylist<integer> arraylist = new arraylist<integer>(); while (!stack.isempty()) { arraylist.add(stack.pop()); } return arraylist; } } class listnode { public int val; public listnode next; public listnode() { } public listnode(int val) { this.val = val; } }
以上所述是小编给大家介绍的java解决no enclosing instance of type printlistfromtailtohead is accessible问题的两种方案,希望对大家有所帮助。