我的程序的功能是允许用户使用堆来管理任务列表。当前任务基于最快的截止日期。任务对象包含2个字符串,一个名称和一个截止日期。将任务节点添加到堆中没有问题。我的问题是它应该将它添加到堆中,并且它应该在到期日到期时成为当前任务。每当我不添加任何内容时,我的程序就能完美运行,只有当我添加一个任务时,无论我将截止日期设置为什么,新任务都成为最后一个任务。以下是一些例子:
Do Math Homework, 05/04/2015 11:00 // Read in from text file and added to heap
Do Grocery Shopping, 05/03/2015 12:00 // Read in from text file and added to heap
Write Code, 04/30/2015 15:00
// User is asked for input and wants to add "Write Code" to Tasklist, notice the date.
Output when I run program:
Do Grocery Shopping, 05/03/2015 12:00 // This is correct order
Do Math Homework, 05/04/2015 11:00 // This is correct order
Write Code, 04/30/2015 15:00 // Problem here
// The added task always gets output last no matter what the date is
主类:
public static Heap addTask( Heap h ){
Task newTask = new Task( "", "" ); // Create a new empty task.
Scanner input = new Scanner(System.in);
System.out.println("Enter the Task Name: ");
newTask.setName( input.nextLine() );
System.out.println("Enter the Due Date: ");
newTask.setDueDate( input.nextLine() );
Node n = new Node( newTask ); // Sets the data of new task and adds to Node.
h.addNode( n );
return h;
}
任务类:
public class Task {
private String name;
private String dueDate;
public Task( String n, String d ){
name = n;
dueDate = d;
}
// Maybe my compareTo() is wrong?
public int compareTo( Task t ){
return dueDate.compareTo( t.getDueDate() );
}
堆类:
public class Heap {
private ArrayList<Node> heap;
public Heap(){
heap = new ArrayList<Node>();
}
public int getPLoc( int i ){
return ( i - 1 ) / 2;
}
public Node getNodeAt( int i ){
if( heap.get(i) == null ){
System.out.println("Item does not exist.");
return null;
}else{
return heap.get(i);
}
}
public void addNode( Node n ){
heap.add(null);
int index = heap.size() - 1;
while( index > 0 && getNodeAt(getPLoc(index)).getData().compareTo( n.getData() ) > 0 ){
heap.set(index, getNodeAt(getPLoc(index)));
index = getPLoc(index);
}
heap.set(index, n);
}