如何以有序的方式将文本文件插入链接列表? Java的

时间:2013-10-13 23:11:27

标签: java text linked-list java.util.scanner

我有一个文本文件如下:

head    World
tail    westerly
head    duck
head    doorstop
position    3   kickplate
tail    Nested
head    Kite
tail    easterly
head    cavello
head    weatherstripping
position    6   sheathing
head    street
tail    screen
head    ducting
head    thermopane
position    6   collaborate
head    mouse
tail    vane
head    tale
tail    tail
head    window
head    caulking
position    5   termostat
head    green
tail    northernly
head    platipus
head    stoop
position    12  team
head    asia
tail    africa
head    america
head    europe
position    15  roundRobin

我需要能够将此文本文件插入到LinkedList中。虽然,我不能在列表中插入单词“head”,但我必须在头部,尾部或位置“无论位置”插入第二个单词。我该怎么做呢?例如,我必须在头部(第一行)插入World,然后在尾部(第二行)插入Westerly。它必须以我可以采取“位置3踢板”并将踢板放在位置3的方式完成,因为不同物品的格式不同。

到目前为止,这是我的代码,我所做的只是一个LinkedList TarepList并将所有文本文件放入其中,但它们不是任何顺序。

import java.util.*;
import java.io.*;
import java.util.List;

public class TarepList {

public static void main(String [] args) {

    List<String> TarepOne = new java.util.LinkedList<String>();

    try{
        File file = new File("AddData.txt");
        Scanner calladd; 
        calladd = new Scanner(file);

    while(calladd.hasNext()){
        String item = calladd.next();
        TarepOne.add(item);
    }

    for(int i = 0;i < TarepOne.size(); i++){
        System.out.println(TarepOne.get(i));
    }


    calladd.close();
        } catch (Exception e){
        System.out.println("file not found");
    } // catch




    // Open the AddData.txt file and add the items appropriately to the list


    // Print out the entire list


    // Open the RemoveData.txt file and remove the specified items from the     list


    // Print out the entire list


    // Empty the TarepOne list and then print out the entire list

}
}

1 个答案:

答案 0 :(得分:0)

你需要做一些解析。这将发生在while循环中。像这样:

while (calladd.hasNext()) {
    String command = calladd.next();
    if (command.equals("head") {
        String item = calladd.next();
        // put item at the beginning
    } else if (command.equals("tail") {
        String item = calladd.next();
        // put item at the end
    } else if (command.equals("position")) {
        int pos = calladd.nextInt();
        String item = calladd.next();
        // put item at position pos
    }
}