[英]Java scanner class, reading from a file
搜索某些東西時如何在Java中執行OR約束。
可以說我有一個txt文件,想要搜索該文件以獲取
汽車或自行車
我該如何實現呢?
從您的短語判斷來看,您似乎已經能夠讀取文件中的單詞。 如果是這樣,您可以這樣做
if("car".equalsIgnoreCase(word) || "bike".equalsIgnoreCase(word)) {
// whatever
}
這里的關鍵是其中的雙杠( ||
):這是LOGICAL OR
。 該行是這樣做的:
boolean hasCar = "car".equalsIgnoreCase(word);
boolean hasBike = "bike".equalsIgnoreCase(word);
if(hasCar || hasBike) {
// whatever
}
如果您需要從Java文件中讀取單詞,則可以通過多種方式來實現。 我通常使用java.util.Scanner
Scanner sc = new Scanner(new File(filename));
while(sc.hasNext()) {
String word = sc.next();
// add search logic here
}
如果您不僅需要像這樣的簡單搜索,還需要提供更多嘗試操作的上下文。
Scanner in = new Scanner(new FileReader("myfile.txt"));
boolean found = false;
while (in.hasNext())
{
String word = in.next();
if (word.equals("bike") || word.equals("car"))
{
found = true;
break;
}
}
if (found) System.out.println("I FOUND IT!!!");
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.