Java가 No enclosing instance of type PrintListFromTailToHead is accessible 문제를 해결하는 두 가지 방안

3197 단어 javaenclosinginstance
오늘 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 클래스로 정의합니다.
두 번째:
PrintListFromTailToHead 클래스 외부에서 내부 클래스 ListNode를 정의합니다.
두 가지 해결 방법:
첫 번째:

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;
}
}
위에서 설명한 자바는 No enclosing instance of type PrintList From Tail To Head is accessible 문제를 해결하는 두 가지 방안으로 여러분에게 도움이 되기를 바랍니다.

좋은 웹페이지 즐겨찾기