0

我有一个文本文件如下:

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

}
}
4

1 回答 1

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
    }
}
于 2013-10-13T23:19:22.373 回答