今天在編譯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問題的兩種方案,希望對大家有所幫助。
新聞熱點
疑難解答