簡體   English   中英

從文件中打印數據

[英]Printing data from a file

因此,我一直試圖在文件中搜索句子中的關鍵字並打印找到的句子。 我有一些代碼在輸入中搜索匹配的單詞,但是我不知道如何根據用戶輸入在文件中搜索那些關鍵字。 我朝着正確的方向前進嗎?

static String [ ] matchwords = {"get","think","go", "talk","choose"};
static List words = Arrays.asList(matchwords);

public static void main(String args[]){
    Scanner console = new Scanner(System.in);
    String input = console.nextLine().toLowerCase();
    List line = Arrays.asList(input.split(" "));
    int numberofWords =0;

    numberofWords = check(line, numberofWords);
    System.out.println("Matched words is : "+numberofWords);
}

public static int check(List list, int count){
    for(int j=0;j<list.size();j++)
        if(words.contains(list.get(j))){
            list.remove(j);
            check(list, count);
            count++;
        }

    return count;
}

對要查找的每個單詞使用contains() ,並在遇到匹配項后增加一個計數器。

String input = console.nextLine().toLowerCase();
List<Integer> matches = new ArrayList<Integer>();
for (int i = 0; i < matchwords.length; i++) {
    if (input.contains(matchwords[i]) {
        matches.add(i); // stores indices of the words that had a match
        // matches.length will be the number of matches (previously count)
    }
}

暫無
暫無

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

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