-2

Let's say I am trying to assign variable hit to true or false depending on whether user input is equal to either "yes" or "y" (I have the .toLowerCase() handled). Is there a way I can use .equals in a way that compares one string to two other strings all in the same line? I did a bit of searching, but I did not find anything, possibly because of the wording of a question like this. My line of code:

boolean hit = kb.next().toLowerCase.equals("y"); // Change something to see if kb.next() also equals "yes"

So, to repeat, the code should see whether string a equals string b or string c. If it is impossible to do this on one line, then just say so in the comments or provide an alternative that is hopefully concise.

RW77
  • 64
  • 1
  • 8
  • Either use a set of "y" and "yes" and check using contains or assign it to a variable and check using equals. – khachik Mar 08 '21 at 18:32
  • Also check https://stackoverflow.com/questions/10205437/compare-one-string-with-multiple-values-in-one-expression – Progman Mar 08 '21 at 18:32
  • So the answer is no. – RW77 Mar 08 '21 at 18:36
  • just curious... why on Earth would you care if it's "on one line" (I assume you mean the code for both checks is written on same line in the source file?) or not ? – 62mkv Mar 08 '21 at 18:37
  • Use regex String regex = "y(es)?"; System.out.println("y".toLowerCase().matches(regex)); System.out.println("yes".toLowerCase().matches(regex)); System.out.println("n".toLowerCase().matches(regex)); System.out.println("no".toLowerCase().matches(regex)); – Ryan Mar 08 '21 at 18:39
  • @62mkv - I would prefer not to create a temp variable to store kb.next() and then compare it to both of them in a separate line. – RW77 Mar 08 '21 at 18:43
  • you could write 'if (kb.equalsIgnoreCase("y") || kb.equalsIgnoreCase("yes")) {..} '. – 62mkv Mar 08 '21 at 18:46

1 Answers1

1

You can't use equals to compare with two strings unless you call it twice, like this:

String input = kb.next().toLowerCase(); 
boolean hit = input.equals("y") || input.equals("yes");

You could alternatively use a regex:

boolean hit = input.matches("y(es)?");

Or if you don't mind matching the string "ye" as well as "y" and "yes", you could use startsWith:

boolean hit = "yes".startsWith(input);
kaya3
  • 47,440
  • 4
  • 68
  • 97
  • I chose the third because "ye" can also be interpreted as "yes" in most conversations. Thanks for your help. – RW77 Mar 08 '21 at 18:40