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.
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\\??"))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With