簡體   English   中英

一次讀取一行文本文件,並將單詞拆分為Array Java

[英]Read in a text file 1 line at a time and split the words into an Array Java

用戶選擇一個文本文件。 我拿起文件,將1行分割成單個單詞。 然后,我使用if語句查看其中一個單詞是否等於單詞“ the”。 第一行中有“ the”一詞,但不是說存在。它不是第一個(即我知道這是一團糟,但這是我正在使用的東西)。在這一刻)

try {
    BufferedReader br = new BufferedReader(new FileReader(test));
    //String text = "";
    String line = br.readLine();

    //while (line != null)
    if(line != null) {
        for(int j = 0; j < 20; j++) //loops through first 20 lines {
            if(line != null) {
                //text += line;
                String[] words = line.toLowerCase().split(" ");
                for(int i = 0; i < words.length; i++){//loops array of split up words
                    if(words[i].equals("the")) {
                        System.out.println("Found T H E");
                    } else {
                        System.out.println("Didn't find the");
                        System.out.println(words[i]);
                    }
                    line = br.readLine(); 
                }
            } else {
                System.out.println("");
            }
        }
    } else {
        System.out.println("It's null");
    }
    br.close();
} catch (Exception ex) {
    System.err.println("Error" + ex);
}

嘗試移動線

line = br.readLine(); 

循環外

for(int i = 0; i < words.length; i++){

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM