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")){
The shortest I can think of is :
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.
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())) { ...
Two ways:
Using equals:
if (yesOrNo.equals("Y") ||
yesOrNo.equals("y") ||
yesOrNo.equals("Yes") ||
yesOrNo.equals("yes")) {
//...
}
Using regexp (shorther than using || multiple times):
if (yesOrNo.toLowerCase().matches("y|yes")) {
//...
}
Try:
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.
Like this:
if (yesOrNo.equals("Y") || yesOrNo.equals("y") || yesOrNo.equals("Yes") || yesOrNo.equals("yes")){
//...
}
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")) {
Related
I want to make my do loop run while the input the user made is not equal to the required letters (a-i) For some reason,even when i input the proper letters, it loops forever.
I've tried using switch cases as well as != inside the comparison.
Here is my code:
do {
System.out.println("Please enter the location of your battleship, starting with the first letter value. Make sure it is from the letters a-i.");
lL1=in.nextLine();
if (!lL1.equals("a")||!lL1.equals("b")||!lL1.equals("c")||!lL1.equals("d")||!lL1.equals("e")||!lL1.equals("f")||!lL1.equals("g")||!lL1.equals("h")||!lL1.equals("i")){
System.out.println("Invalid Input. Try again.");
}//End if statement
}while(!lL1.equals("a") || !lL1.equals("b") || !lL1.equals("c") || !lL1.equals("d") || !lL1.equals("e") || !lL1.equals("f") || !lL1.equals("g") || !lL1.equals("h") || !lL1.equals("i"));
My skills in Java are limited but this should work, unless i'm missing something obvious. Any help would be amazing!
Instead of using an operator for each case of the input, you might want to create a list of the accepted answers and then your condition will look like:
while answer is not in accepted answers, ask another input
An example would be:
Scanner scanner = new Scanner(System.in);
List<String> acceptedAnswers = Arrays.asList("a", "b", "c", "d", "e", "f", "g", "h", "i");
String input;
do {
System.out.println(
"Please enter the location of your battleship, starting with the first letter value. Make sure it is from the letters a-i.");
input = scanner.nextLine();
} while (!acceptedAnswers.contains(input));
scanner.close();
System.out.println("Got correct input: " + input);
If you have a negation you need AND to join the conditions not OR.
That's because if you or some not-ed values, they form an and.
Let me explain better.
If you input a, then the first is false (because you not it), and the others are true, so the or condition make the result be true.
You should instead group all the ors and then not it.
e.g.
!(lL1.equals("a") || lL1.equals("b") || lL1.equals("c") || lL1.equals("d") || lL1.equals("e") || lL1.equals("f") || lL1.equals("g") || lL1.equals("h") || lL1.equals("i"))
Please try this:
char lL1;
Scanner scanner = new Scanner(System.in);
do {
System.out.println("Please enter the location of your battleship, starting with the first letter value. Make sure it is from the letters a-i.");
lL1=scanner.next().charAt(0);
}while(lL1!='a' && lL1!='b' && lL1!='c' && lL1!='d' && lL1!='e' && lL1!='f' && lL1!='g' && lL1!='h' && lL1!='i');
Since you are only getting a single character, you can check that it does not match either [a to i] characters as shown above. This is the shortest way to do so by making the check as the condition of the loop. If it fails then the loop will be called.
For some reason, when I have multiple correct strings, the statement keeps repeating
do {
System.out.println("Enter Service Code");
Scanner a = new Scanner(System.in);
serviceCode = a.nextLine();
} while (!serviceCode.equals("ORB1") || !serviceCode.equals("ORBH") ||
!serviceCode.equals("ISS5") || !serviceCode.equals("ILLOYDS") ||
!serviceCode.equals("DLAB") || !serviceCode.equals("LEOM7") ||
!serviceCode.equals("MOON2"));
However, when there's just one string that the code checks against. The do while statement works fine and will stop looping when the correct input is entered
do {
System.out.println("Enter Service Code");
Scanner a = new Scanner(System.in);
serviceCode = a.nextLine();
} while (!serviceCode.equals("ORB1"));
If you enter "ORB1", "!serviceCode.equals("ORB1")" will return false but the others will return true; and you are using the "OR" operator. So, this sentence :
!serviceCode.equals("ORB1") || !serviceCode.equals("ORBH") ||
!serviceCode.equals("ISS5") || !serviceCode.equals("ILLOYDS") ||
!serviceCode.equals("DLAB") || !serviceCode.equals("LEOM7") ||
!serviceCode.equals("MOON2")
will always be true. You need to use the "AND" operator
!serviceCode.equals("ORB1") && !serviceCode.equals("ORBH") &&
!serviceCode.equals("ISS5") && !serviceCode.equals("ILLOYDS") &&
!serviceCode.equals("DLAB") && !serviceCode.equals("LEOM7") &&
!serviceCode.equals("MOON2")
Your comparison can never return false. it's either A or B.
so, if you were to say:
if ( !A OR !B ){
--> Input = A => true (because !B returns true)
--> Input = B => true (because !A returns true)
--> Input = C => true (because !A returns true)
Change your OR (||) by AND (&&)
Also: declare and instantiate your Scanner before your loop.
A better approach would be create a Listof string which includes the valid codes and check if that list contains the provided user input.
List<String> validServiceCodes = Arrays.asList("ORB1", "ORBH", "ISS5", "ILLOYDS", "DLAB", "LEOM7", "MOON2" );
do {
System.out.println("Enter Service Code");
Scanner a = new Scanner(System.in);
serviceCode = a.nextLine();
} while (!validCodes.contains(validServiceCodes));
I am developing an personal assistant and it can answer to questions like "How are you?" but I don't want to define the same answers to similar questions such as "How do you feel?" and etc.I tried to use || after contains but it just didn't work.How can I use || in this kind of situation??Can someone help me out please?
Code:
else if (Text.getText().toString().contains("see you later")){
saySomething("Good bye sir"); }
The code I tried:
else if (Text.getText().toString().contains("see you later"||"goodbye")){
saySomething("Good bye sir"); }
String s = text.getText().toString();
// disjunction of 2 contains
boolean orResult = s.contains("see you later") || s.contains("goodbye");
// alternative using regex
boolean regexResult = s.matches(".*(see you later|goodbye).*");
My idea would be to reduce the condition in if clauses like:
boolean isSeeLaterTxt = Text.getText().toString().contains("see you later");
boolean isGoodByeTxt = Text.getText().toString().contains("goodbye");
else if ( isSeeLaterTxt || isGoodByeTxt )) {
saySomething("Good bye sir");
}
That's my short suggestion. The code will be better readable. And you can later change flexible the condition.
else if (Text.getText().toString().contains("see you later"||"goodbye")){
saySomething("Good bye sir"); }
instead of this try below code
else if (Text.getText().toString().contains("see you later") || Text.getText().toString().contains("goodbye")){
saySomething("Good bye sir"); }
I am looking for a statement that checks if the input is either: yes, y, no, n.
It should also ignore whether or not there are big or small letters. I have been searching here for a while but couldn't find an answer I understood. Is there a way to add more then just "yes" to the if statement?
String result;
do {
System.out.print("Bigger the better");
result = scanner.nextLine();
if (!("yes".equals(result))) {
System.out.println("Invalid answer, try again");
}
} while(!result.matches("[A-ZÅÄÖa-zåäö]+"));
You could use
if (result.matches("(?i)Y(es)?|N(o)?")) {
...
You can OR your conditions using double pipes ||, like so:
if (result.equals("yes") || result.equals("no") || result.equals("y") || result.equals("n"))
Make your result a lower case by:
result.toLowerCase()
And then you can compare to any of the strings ("yes","no","y","n") by using equals() as you did, and using 'or' (||).
result.toLowerCase();
if(result.length()>1 && !result.equals("yes") &&!result.equals("no")){
System.out.println("wrong input");
} else if(result.charAt(0)=='y') {
System.out.println("good answer");
}else if(result.charAt(0)=='n') {
System.out.println("Invalid answer, try again");
}
it will check ether the user will type "yes" or plain "y", or "no" or plain "n"
So I am writing a code that ask a user if they would like to be recommended a new pet. I give them a message dialog the ask them to enter Y for Yes and N for No. This is my code do far and there is something I am not getting. The big question is how do I test if the value they entered is Y or N. The answer they give can either be lower case or upper case. How do I code this?
public static void aPet()
{
char answer;
String newPet;
newPet = JOptionPane.showInputDialog(null,"Would you like to recommend another pet?(Y), or Stop (N)","Another Recommendation?", JOptionPane.QUESTION_MESSAGE);
answer = newPet.charAt(0);
if (answer == y || answer == Y)
{
//methods to recommend pet
}
if (answer == n || answer == N)
{
System.exit(-1);
}
}
You need to use actual character literals, not just the letter:
if (answer == 'y' || answer == 'Y')
Characters are denoted in code by surrounding the letter with single quotes (they can also be denoted in other ways, but this is the simplest).
You can read about this on The Java Tutorials > Primitive Data Types which says, among other things:
Always use 'single quotes' for char literals and "double quotes" for String literals.
You are missing single quotes around the values 'y' and 'n':
Try this:
char answer = newPet.charAt(0);
if('y' == answer || 'Y' == answer) {
// recommend pet
} else {
// exit
}
OR
Edited
if(newPet.matches("y|Y")) {
// recommend pet
} else {
// exit
}
OR
if("y".equalsIgnoreCase(newPet)) {
// recommend pet
} else {
// exit
}
You can use Character#toUpperCase() like that:
if (Character.toUpperCase(answer) == 'Y')
{
//methods to recommend pet
}