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"
Related
I need help with a SIMPLE Y/N Condition for my program. I don't really get it to work as I want to.
Unfortunately all the other topics I find is very confusing. I'm a very novice student in programming.
I want a Y/N Condition that wont crash and is not CASE SENSITIVE. so if Y or y it goes back to another menu, if n and N is just stop the program and if anything else is typed in it will loop until the Y or N conditions are met.
This is what i wrote:
String input = ScanString.nextLine();
while (!"Y".equals(input) || !"y".equals(input) || !"N".equals(input) || !"n".equals(input)) {
System.out.println("Please enter Y/N (Not case sensitive): ");
input = ScanString.nextLine();
}
if ("Y".equals(input) || "y".equals(input)) {
meny1();
} else if ("N".equals(input) || "n".equals(input)) {
}
When it runs, whatever I put in, it won't break the while loop.
while (!"Y".equals(input) || !"y".equals(input) ||... means "keep looping while the input isn't 'Y' or the input isn't 'y' or...". By definition, one of those conditions will always be true.
The simplest way to do what you're looking for would be a case insensitive comparison, and an and (&&) rather than or operator:
while (!input.equalsIgnoreCase("Y") && !input.equalsIgnoreCase("N")) {
That means "keep looping while the input isn't 'Y' or 'y' and the input isn't 'N' or 'n'.
Or the same in Yoda-speak, since you were using Yoda-speak:
while (!"Y".equalsIgnoreCase(input) && !"N".equalsIgnoreCase(input)) {
Try this
while (!("Y".equalsIgnoreCase(input)) && !("N".equalsIgnoreCase(input))) {
}
Or
String[] validInputs = { "Y", "N" };
while(!Arrays.asList(validInputs).contains(input.toUpperCase())) {
}
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
}
I have the fallowing code
while (b == true){
System.out.print("input the account balance without tax: ");
int inner = input.nextInt();
List[x]=inner;
x=x+1;
}
and I want to check if my user inputs a word it would do:
b =false
So I would exit this loop. In python we had try() and except.
I don't really know what to do in java.
I think you want to change
while (b == true){
to use Scanner.hasNextInt() like
while (input.hasNextInt()){
If you must do a while(true) statement, which isn't good programming practice, the final code snippet would look something like this,
boolean someCondition = true;
while(true){
if(someCondition == false){
break;
}
//and here you would put something that would make that check condition eventual
//false to break the loop
}
This is prone too error but would work for your purposes.
That being said, the answer Elliot gave is the correct one and worth considering.
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed last year.
It executes correctly the first time, but:
It keeps printing "Please try again (Y/N)?" no matter what the
input is after asking to continue.
I am unsure if != is appropriate to use for String comparison. I want to say while
loopChoice "is not" Y or N, keep asking.
while(isLoop) {
// Ask for user input
System.out.print("Enter hours worked: ");
hoursWorked = scn.nextInt();
System.out.print("Enter rate per hour: ");
payRate = scn.nextInt();
scn.nextLine();
// Call functions to compute stuff
...
// Print results
...
System.out.print("\nDo you want to continue (Y/N)? ");
loopChoice = scn.nextLine().toUpperCase();
while(loopChoice != "Y" || loopChoice != "N") {
System.out.print("\nPlease try again (Y/N)? ");
loopChoice = scn.nextLine().toUpperCase();
}
switch(loopChoice) {
case "Y":
isLoop = true;
System.out.print("\n");
break;
case "N":
isLoop = false;
System.out.println("Terminating program...");
scn.close();
System.exit(0);
break;
default:
System.out.println("Your input is invalid!");
isLoop = false;
System.out.println("Terminating program...");
scn.close();
System.exit(0);
break;
}
}
You should compare with String equals
while (!loopChoice.equals("Y") && !loopChoice.equals("N"))
Also, replace the or operator with and operator
That's not how you compare strings in Java.
There is also a logical error in your code, as the string can't be both Y and N at the same time, you have to use && instead of ||. As long as the choice is neither Y or N, you want to continue the loop. If it is any of them, you want to stop. So && is the correct choice here.
To check if two strings are equal, you have to use .equals(obj)
while (!loopChoice.equals("Y") && !loopChoice.equals("N")) {
The reason for this is that == compares object references, and two Strings are most often not the same object reference. (Technically, they can be the same object reference, but that's not something you need to worry about now) To be safe, use .equals to compare Strings.
To avoid a possible NullPointerException in other situations, you can also use:
while (!"Y".equals(loopChoice) && !"N".equals(loopChoice)) {
You cannot use loopChoice != "Y", since "Y" is a String. Either use:
loopChoice != 'Y', or
"Y".equals(loopChoice)
Alternatively, use "Y".equalsIgnoreCase(loopChoice).
Case switching is also not possible for Strings if you use Java 1.6 or earlier. Be careful.
You need to know that OR Operation will return true if one of the two condition is true , so logically if you Enter Y , so you ask if the input is not equal Y so the answer is false then you will go to the next part in your condition if the input not equal N so the answer is True , so your finally result will be (True || False = True ) and then you will entered to while loop again
so the true condition is (the input not equal Y && not equal N)
You have fallen into the common early gap between checking equality of objects versus the values of objects. (You can see a quick list of string comparison information [here]
(http://docs.oracle.com/javase/tutorial/java/data/comparestrings.html)
What you wrote asks whether the object loopChoice is the same object as the string constant "Y" or the string constant "N" which will always return false. You want to ask whether the value of object loopChoice is the same as the value of string constant "Y".
You could rewrite your code as follows:
System.out.print("\nDo you want to continue (Y/N)? ");
// get value of next line, and trim whitespace in case use hit the spacebar
loopChoice = scn.nextLine().trim();
while (!("Y".equalsIgnoreCase(loopChoice) || "N".equalsIgnoreCase(loopChoice)) {
System.out.print("\nPlease try again (Y/N)? ");
loopChoice = scn.nextLine().toUpperCase();
}
Note, I like to put the constant value first for clarity. The general form for determining whether the value of two strings is the same is String1.equalsIgnoreCase(String2).
For some reason this program won't loop correctly, its supposed to wait for user input, then decide on weather or not it should loop.Instead, it skips the user input part, goes straight to deciding it needs to loop, then allows user input to be taken into account.
For example, it asks for a number, i type 5, then it says "would you like to go again?" "Please use either yes or no, case sensitive!" "would you like to go again?".After it has run that it will accept user input,I thought about using a sleep(2000),but I don't want it to just skip over and assume the user didn't put anything in.I am stumped! keep in mind this is my second day working with java. I am a newbie and this is only the 3rd program i am working on. I had this issue on another program but i managed to fix it just fine.However this one seems to not want to work in the same fashion despite the fact that i did framework exactly the same.
do {
System.out.println("would you like to go again?");
if (input.hasNextLine()){
again = input.nextLine();
if (again.equals("yes")){
yon2 = false;
dateconverter.main(args);
}else if (again.equals("no")){
System.out.println("good bye");
Thread.sleep(4000);
System.exit(0);
}else{
yon2 = true;
System.out.println("Please use either yes or no. caps sensative!");
}
}
} while (!(yon2 = false));
Java loops correctly. However, yon2 = false is an assignment and not a comparison.
Thus the loop is equivalent to:
do {
// ..
yon2 = false; // assign! :(
} while (!yon2);
So Java is doing exactly what it was told to do.
Now, with that out of the way, I believe the other issue is being confused about the variables usage. Consider this:
boolean askAgain = true;
do {
System.out.println("would you like to go again?");
if (input.hasNextLine()){
String again = input.nextLine();
if (again.equals("yes")){
// Finally done asking
askAgain = false;
dateconverter.main(args);
} else if (again.equals("no")){
System.out.println("good bye");
Thread.sleep(4000);
System.exit(0);
} else {
// If we're here, we still need to ask again
System.out.println("Please use either yes or no. caps sensative!");
}
} else {
// no more lines! do something sensible
System.exit(0);
}
// Loop while we need to ask again!
// Note that the negative is removed
} while (askAgain);
However, taking a second to refactor this allows for something easier to read later and avoids the dealing with a flag entirely:
boolean promptKeepPlaying (Scanner input) {
while (input.hasNextLine()){
System.out.println("would you like to go again?");
String again = input.nextLine();
if (again.equalsIgnoreCase("yes")){
return true;
} else if (again.equalsIgnoreCase("no")){
return false;
} else {
System.out.println("Please use either yes or no.");
}
}
// no more lines
return false;
}
// somewhere else
if (promptKeepPlaying(input)) {
// restart game
dateconverter.main(args);
} else {
// exit game
System.out.println("good bye");
Thread.sleep(4000);
System.exit(0);
}
You've got a bug in your program. You've accidentally written an assignment instead of an equality test.
However, the real lesson here is that you should not be writing cumbersome == and != tests involving booleans. There are simpler, more elegant and less error prone ways of writing the tests. For example, assuming that condition is a boolean.
condition == true is the same as condition
condition == false is the same as !condition
!(condition == false) is the same as condition
condition == condition2 is the same as !(condition ^ condition2)1.
There is a real benefit in taking the time to write your code simply and elegantly.
1 - This is an example where == is more elegant ... but the ^ exclusive-or operator avoids the accidental assignment trap.