Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I create an OR statement when comparing strings?

My code is:

import java.util.Scanner;

class mainClass {
    public static void main (String [] args) {          
        secondaryClass SCO = new secondaryClass();          
        Scanner scanner = new Scanner(System.in);           
        String randomtext = scanner.nextLine();    
        if(randomtext.equals("What is the time"))
        {
            SCO.giveTime();               
        }
        else if (randomtext.equals("Whats the time"))
        {       
            SCO.giveTime();             
        }
    }       
}

I would like to know if I could replace that if else statement with some thing along the lines of:

import java.util.Scanner;

class mainClass {
    public static void main (String [] args) {  
        secondaryClass SCO = new secondaryClass();      
        Scanner scanner = new Scanner(System.in);       
        String randomtext = scanner.nextLine();
        if(randomtext.equals("What is the time" || "Whats the time"))
        {
            SCO.giveTime();
        }       
    }
}

SCO is the object for my second class by the way, it outputs the time perfectly.

like image 887
Aazim Abdul Avatar asked Apr 15 '26 03:04

Aazim Abdul


1 Answers

You can one comparison using regex, but it only moves the OR from java to regex:

if (randomtext.matches("(What is the time)|(Whats the time)"))

Although you can express it more succinctly:

if (randomtext.matches("What(s| is) the time"))

and even make an apostrophe and/or a question mark optional:

if (randomtext.matches("What('?s| is) the time\\??"))
like image 186
Bohemian Avatar answered Apr 17 '26 17:04

Bohemian



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!