将输入文件中的列表打印到屏幕

时间:2017-04-22 04:14:41

标签: java

Vegetable   Fruit       Desert
Carrot      banana       cake
Cucumber    apple       ice cream
Lettuce     orange      cookies 
Broccoli    grapes      donuts

我想知道是否有一种特定的方式来编写程序,以便只有水果列表存储在输入文件的数组列表中。所以,基本上我想要它做的是将它打印到屏幕上: enter image description here

所以,到目前为止,这就是我所拥有的,老实说,我无法弄清楚从哪里开始。任何事情都会受到赞赏。

public static void main(String[] args) throws IOException {
        String line;  
        ArrayList<String> names = new ArrayList<>();
        String filename = "list.txt";
        File inputFile = new File(filename);
        Scanner in = new Scanner(inputFile);
        FileReader file = new FileReader(inputFile);
        BufferedReader reader = new BufferedReader(file);
        line = reader.readLine();
        System.out.println(line);
        while((line = reader.readLine()) != null)
            if(line.equals("Vegetable   Fruit       Desert")){
                break;
            }
        while((line = reader.readLine()) != null){
            names.add(line);
        }
        in.close();
        reader.close();       
    }
}

1 个答案:

答案 0 :(得分:2)

只需分割线条并存储第二个元素,即水果元素。我在你的第二个while循环中修改了代码:

public static void main(String[] args) throws IOException {
    String line;

    ArrayList<String> names = new ArrayList<>();
    String filename = "list.txt";
    File inputFile = new File(filename);
    FileReader file = new FileReader(inputFile);
    BufferedReader reader = new BufferedReader(file);
    // remove first line
    line = reader.readLine();

    while((line = reader.readLine()) != null){
        String[] words = line.split("\\t+");
        names.add(words[1]);
    }

    System.out.println(names);

    reader.close();
}