简体   繁体   中英

Java scanner class, reading from a file

How do i carry out a OR constraint in java when searching for for something.

Lets say i have a txt file and want to search the file for

car OR bike

how do i implement this?

Anywhere in the file

Judging by the way you phrase it, it looks like you already have the ability to already read words from the file. If that's the case, you would do this

if("car".equalsIgnoreCase(word) || "bike".equalsIgnoreCase(word)) {
    // whatever
}

The key here is that double bar ( || ) in there: that's a LOGICAL OR . That line is the as doing this:

boolean hasCar = "car".equalsIgnoreCase(word);
boolean hasBike = "bike".equalsIgnoreCase(word);

if(hasCar || hasBike) {
    // whatever
}

If you need to read words from a file in Java, there's a number of ways you could do it. I typically use java.util.Scanner

Scanner sc = new Scanner(new File(filename));
while(sc.hasNext()) {
    String word = sc.next();
    // add search logic here
}

If you need to do more than a simple search like this, you're going to have to give more context of what you're trying to do.

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!!!");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM