简体   繁体   中英

How to make a x = y or z statement in Java

In my program, I have a String called yesOrNo that is a keyboard input. I created an if statement to test if yesOrNo is one of the following : "Y", "y", "Yes", "yes" by using the || operator.

I got the error message: The operator || is undefined for the argument type(s) java.lang.String, java.lang.String. What is the right way to do something like this? Thanks.

    Scanner keyboard = new Scanner(System.in);
    String yesOrNo = keyboard.nextLine();
    System.out.println(yesOrNo + "?" );

    if (yesOrNo.equals("Y" || "y" || "Yes || "yes")){

我能想到的最短的是:

if (yesOrNo.equalsIgnoreCase("Y") || yesOrNo.equalsIgnoreCase("Yes"))

Your syntax is invalid. It needs to have separate clauses:

if(yesOrNo.equals("Y") || yesOrNo.equals("y")...)

or cleaner would be if you used regex:

if(yesOrNo.matches("Y|y|Yes|yes")) { 
    // Code.
}

Extra Reading

  • You should look at the String Docs . They detail all sorts of useful stuff.

  • Read up on Regex . It makes complex String comparison very simple.

  • Finally, look at the different Operators to see what kind of logical statements you can form, with the correct syntax.

Two ways:

  1. Using equals :

     if (yesOrNo.equals("Y") || yesOrNo.equals("y") || yesOrNo.equals("Yes") || yesOrNo.equals("yes")) { //... } 
  2. Using regexp (shorther than using || multiple times):

     if (yesOrNo.toLowerCase().matches("y|yes")) { //... } 

Alternatively, you could create a list of acceptable answers and check whether the answer is in that list.

List<String> kindOfYes = Arrays.asList("yes", "y", "okay", "righto");
if (kindOfYes.contains(yesOrNo.toLowerCase())) { ...

Try:

if(yesOrNo.equals("Y") || yesOrNo.equals("y") 
   || yesOrNo.equals("Yes") || yesOrNo.equals("yes"))

Like this:

if (yesOrNo.equals("Y") || yesOrNo.equals("y") || yesOrNo.equals("Yes") || yesOrNo.equals("yes")){
    //...
}
if (yesOrNo.equals("Y") || yesOrNo.equals("y") || yesOrNo.equals("Yes")  || yesOrNo.equals("yes")) 

What about the next code?

String yesOrNo = keyboard.nextLine();
if (yesOrNo.toLowerCase().charAt(0) == 'y') {
    //  
}

NOTE : Do you think there's a quicker way? I think not.

Your program syntax is wrong.

This is correct:

Scanner keyboard = new Scanner(System.in);
    String yesOrNo = keyboard.nextLine();
    System.out.println(yesOrNo + "?" );

    if(yesOrNo.equals("Y") || yesOrNo.equals("y") || yesOrNo.equals("Yes") || yesOrNo.equals("yes")) {

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