【问题标题】:How do you insert a text file into a Linked List in an orderly fashion? Java如何以有序的方式将文本文件插入到链接列表中?爪哇
【发布时间】:2013-10-13 23:11:27
【问题描述】:

我有一个文本文件如下:

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

}
}

【问题讨论】:

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


    【解决方案1】:

    你需要做一些解析。这将发生在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
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-11-14
      • 2011-10-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多