我有一個程序,從1文件中獲取輸入,將該文件中的每個單詞保存爲一個arrayList中的項目,然後搜索另一個文件中的每個單詞。從那裏我需要它來查看是否從另一個字符串的單詞與搜索的單詞在同一行。邏輯有點混亂,所以我會給你一個例子:使用比較的方法來比較多個單詞到外部文件
這是第一個文件的輸入:
Tuna, Salmon, Hake.
然後每個項目保存到一個ArrayList中:
{Tuna,Salmon,Hake}
從那裏它將搜索具有以下數據的文件:
It costs $5 for tuna that is seared and chunky.
We are out of stock on hake.
It costs $6 for sardines that are tinned.
It costs $4 for tuna that is seared.
然後程序會搜索上面的文件,看到金槍魚在第一行和第四行,鱈魚在第二行,鮭魚沒有出現。
在這裏,我想有例如單詞的列表:
Seared, chunky, out of stock.
並將此列表,看看他們都在同一條線上。換句話說,使得它打印出:
Tuna is seared and chunky
Hake is out of stock
Tuna is seared
到目前爲止,我有完美的代碼,但它只適用於1個字。我的代碼下面是一個例子:
while((strLine1 = br1.readLine()) != null){
for(String list: listOfWords){
Pattern p = Pattern.compile(list);
Matcher m = p.matcher(strLine1);
String strLine2 = "seared" ;
int start = 0;
while (m.find(start)) {
System.out.printf("Word found: %s at index %d to %d.%n", m.group(), m.start(), m.end());
if(strLine1.contains(strLine2)){
System.out.println(list + " is " + strLine2);
}
start = m.end();
}
}
}
那麼這段代碼將打印出來的是:
Tuna is seared (referring to line 1)
Tuna is seared (referring to line 4)
我認爲,爲了實現這一點,我可以在我的if語句和或或者爲strLine2嘗試arrayList,但對於後者,contains方法無法將字符串與arrayList進行比較。
讓我知道我的解釋是否令人困惑,或者您對我如何實現自己的目標有任何想法。由於
原樣,代碼從第一個文件獲取所有數據並在第二個文件中搜索並返回每個單詞的位置。我想檢查更多的單詞而不是烙印。 {炙手可熱,缺貨}。但是你給了我一個使用for循環的想法。 – Digitalwolf
ahhh ok ..所以你通過一個循環與你發現的所有元素? –
剛剛讓我的程序使用arrayList和高級for循環。但感謝您的幫助 – Digitalwolf