繁体   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