0

嗨所以我有这个项目需要我用java编写代码可以说我有这个txt文件:

GoodTitle   Description
Gold        The shiny stuff
Wheat       What wheaties are made of
Wood        To make more ships
Spices      To disguise the taste of rotten food
Tobacco     Smoko time
Coal        To make them steam ships go
Coffee      Wakes you up
Tea         Calms you down

我要做的就是将文本的左侧(goodtitle、gold、wheat、wood 等)放入一个数组列表中,将文本的右侧(描述、闪亮的东西)放入另一个数组列表中。这是我当前的代码:

public void openFile(){
        try{
            x = new Scanner(new File("D://Shipping.txt"));
        }
        catch (Exception e){
            System.out.println("File could not be found");
        }
    }
    public void readFile(){
    while (x.hasNextLine()){
        String a = x.next();
        x.nextLine();
        ArrayList<String> list = new ArrayList<String>();
        while (x.hasNext()){
            list.add(x.next());
        }
        System.out.printf("%s \n", list);
        }
    }
    public void closeFile(){
        x.close();

可能它需要对 readFile 进行一些修改,因为我仍然对如何做到这一点感到困惑。提前致谢...

NOTE=I am not allowed to change the content of the txt file. 
     in my current code i still put the whole thing into 1 arraylist because i am unable to split them.

我需要 toString 方法吗?因为我不知道该怎么做。提前致谢...

4

2 回答 2

0

您必须将左侧读入一个列表,将右侧读入另一个列表。

此代码不正确,因为x.next()实际上并没有返回一列。它怎么知道一列是什么?但它应该让你知道如何去做。

ArrayList<String> listL = new ArrayList<String>();
ArrayList<String> listR = new ArrayList<String>();
while (x.hasNextLine()){
    x.nextLine();
    if (x.hasNext()){
        listL.add(x.next());
    } else {
        listL.add("");
    }

    if (x.hasNext()){
        listR.add(x.next());
    } else {
        listR.add("");
    }
}
System.out.println(listL);
System.out.println(listR);
于 2013-10-17T19:07:24.757 回答
0

如果你愿意使用 a Map<String, String>,也许你可以尝试这样的事情:

public static Map<String, String> getContents() throws IOException {
    final Map<String, String> content = new HashMap<>();
    final Scanner reader = new Scanner(new File("D://Shipping.txt"), "UTF-8");
    while(reader.hasNextLine()){
        final String line = reader.nextLine();
        final String[] split = line.split(" +");
        content.put(split[0], split[1]);
    }
    reader.close();
    return content;
}

public static void main(String args[]) throws IOException{
    final Map<String, String> content = getContents();
    content.keySet().forEach(k -> System.out.printf("%s -> %s\n", k, content.get(k)));
}

我只想指出,该解决方案是使用 Java 8 编写的,您当然可以将其修改为较低的 JDK 级别。

于 2013-10-17T19:11:05.510 回答