Java解决No enclosing instance of type PrintListFromTailToHead is accessible问题的两种方案

网友投稿 168 2023-07-10


Java解决No enclosing instance of type PrintListFromTailToHead is accessible问题的两种方案

今天在编译java程序时遇到如下问题:

No enclosing instance of type PrintListFromTailToHeaXBwHqOicd is accessible. http://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 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 printListFromTailToHead(ListNode listNode) {

Stack stack = new Stack();

while (listNode != null) {

stack.push(listNode.val);

listNode = listNode.next;

}

ArrayList arrayList = new ArrayList();

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 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 printListFromhttp://TailToHead(ListNode listNode) {

Stack stack = new Stack();

while (listNode != null) {

stack.push(listNode.val);

listNode = listNode.next;

}

ArrayList arrayList = new ArrayList();

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问题的两种方案,希望对大家有所帮助。


版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:自己动手写一个java版简单云相册
下一篇:相册管理系统(Java表单+xml数据库存储)
相关文章

 发表评论

暂时没有评论,来抢沙发吧~