Java LinkedList ListIterator

时间:2018-01-11 23:24:40

标签: java listiterator

所以我试图用我的代码完成的任务是从文档读取任务,最终目标是使用ListIterator将优先级(从单独的类给出)排序到LinkedList中。我将所有任务都放到了LinkedList中,但是我在组织部分的某个地方犯了一个错误:

public static void main(String[] args) {
    Task newTask = null;
    LinkedList<Task> list = new LinkedList();
    TaskReader reader = new TaskReader("tasks.txt");

    list.add(reader.provideTask());
    ListIterator<Task> iter = list.listIterator();

    for (int i = 1; i < 20; i++) {
        newTask = reader.provideTask();
        while (iter.hasNext()) {
            if (newTask.getPriority() <= iter.next().getPriority()) {
                iter.add(newTask);
            } else {
                iter.previous();
                iter.add(newTask);
                iter.next();
            }
        }
        iter = list.listIterator();
    }
    while (iter.hasNext()) {
        System.out.println(iter.next().getPriority());
    }
}

现在我获得了大量的输出,我应该只获得20行(并且它们应该按照单独的类给出的优先级从10-1组织)。任何帮助都是极好的!谢谢! 下面是TaskReader类

package versionTwo;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class TaskReader implements TaskProvider {

    private Scanner source = null;

    public TaskReader(String fileName) {
        try {
            source = new Scanner(new File(fileName));
        } catch (FileNotFoundException er) {
            System.out.println("Error opening input file " + fileName + " for reading.");
        }
    }

    public Task provideTask() {
        Task newTask = null;
        if (source != null) {
            try {
                newTask = new Task(source.nextInt(), source.nextInt());
            } catch (Exception ex) {
                System.out.println("Error while trying to read task.");
            }
        }
        return newTask;
    }
}

0 个答案:

没有答案