该程序应该允许用户将整数插入链接列表并保持它们始终排序。我被困在为什么我得到一个空指针异常在这一点后,我的价值回到我的另一种方法。感觉就像我现在在圈子里一样。我有虚拟打印语句来尝试找出问题。获取链接列表空指针,我不明白为什么
类节点:
public class Node {
Comparable data;
Node next;
Node(Node n, Comparable a) {
this.data = a;
this.next = n;
}
}
类SortedLinkedList:
public class SortedLinkedList {
Node head = null;
private Comparable SortedLinkedList;
public SortedLinkedList() {
this.head = null;
this.SortedLinkedList = SortedLinkedList ;
}
public Node insert(Node head, Comparable a){
if (head == null || (head.data.compareTo(a)> 0))
{
System.out.println("In insert first if");
head = new Node(head, a);
//head = new Node(head, 22);
System.out.println("Head = " + head.data + " before return");
return head;
}
Node pointer = head;
while (pointer.next != null)
{
if (pointer.next.data.compareTo(a) > 0){
System.out.println("In insert, in while, in if");
break;
}
pointer = pointer.next;
}
return head;
}
public void print(Node head){
System.out.println("In print outside of for" + head);
for (Node pointer = head; pointer != null ; pointer = pointer.next)
{
System.out.println("In print");
System.out.print(pointer.data);
}
}
}
类TestInteger
public class TestInteger implements Comparable{
// This is the User Interface for manipulating the List
static SortedLinkedList sll = new SortedLinkedList();
public static void nodeMenu() {
Node head = sll.head;
System.out.println(head);
int option;
while(true){
System.out.println();
System.out.println("**** Integer Node Menu ****");
System.out.println("****************************");
System.out.println("** 1. Insert **");
System.out.println("** 2. Delete **");
System.out.println("** 3. Clear **");
System.out.println("** 4. Smallest **");
System.out.println("** 5. Largest **");
System.out.println("** 6. Return to Main Menu **");
System.out.println("****************************");
Scanner sc = new Scanner(System.in);
try{
option = sc.nextInt();
switch (option){
case 1:{
try{
System.out.println("Type an integer to insert: ");
int x = sc.nextInt();
Integer insertItem = new Integer(x);
sll.insert(head, insertItem);
System.out.println("After insert back in case1 head = " + head.data);
sll.print(head);
}catch(InputMismatchException e){
System.out.println("Enter only integers");
sc.nextLine();
}
nodeMenu();
}
它正确地打印在类SortedLinkedList内的实际插入方法而获得一个空指针在类TestInteger。下面是输出:的
1
Type an integer to insert:
5
In insert first if
Head = 5 before return
Exception in thread "main" java.lang.NullPointerException
at CS_240_HW_2.TestInteger.nodeMenu(TestInteger.java:58)
at CS_240_HW_2.Main.mainMenu(Main.java:52)
at CS_240_HW_2.Main.main(Main.java:30)
哇谢谢你我真不敢相信我错过了! – Neophyte 2013-05-06 21:56:14