国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Java > 正文

Java解決No enclosing instance of type PrintListFromTailToHead is accessible問題的兩種方案

2019-11-26 14:01:45
字體:
來源:轉載
供稿:網友

今天在編譯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問題的兩種方案,希望對大家有所幫助。

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 饶阳县| 余庆县| 西乌珠穆沁旗| 黄石市| 论坛| 分宜县| 元谋县| 石家庄市| 舞钢市| 二手房| 龙江县| 龙口市| 珠海市| 高州市| 陆良县| 德清县| 津南区| 商城县| 库伦旗| 盐源县| 洱源县| 安塞县| 黄陵县| 大石桥市| 绿春县| 海林市| 宁阳县| 长乐市| 桑植县| 濮阳市| 扶沟县| 沛县| 满洲里市| 天水市| 贵德县| 开江县| 枣强县| 北辰区| 历史| 拜泉县| 历史|