I'm trying to execute while loop until the user enter Yes or No.
Why can't there be an OR in the testing function instead of AND?
While using OR, it can be either yes or no.
System.out.print("Enter yes or no: ");
String answer = input.getNext();
while (!answer.equals("yes") && !answer.equals("no")) {
System.out.println("Enter ONLY yes or no, please: ");
answer = input.getNext();
}
System.out.println("Thank you!");
Because !answer.equals("yes") && !answer.equals("no") basically says while answer is not "yes" and answer is not "no".
In order to make it an OR you can do it like:
while(!(answer.equals("yes") || answer.equals("no")))
{
}
Which means, while the following condition is not true; condition: answer is "yes" or answer is "no"
while (!answer.equals("yes") && !answer.equals("no")) means that the loop terminates when the condition becomes false. According to de Morgan laws, !(!answer.equals("yes") && !answer.equals("no")) is answer.equals("yes") || answer.equals("no"). That is, the loop terminates when the answer is either "yes" or "no" - that's exactly what you want.
If you change && to ||, the loop would terminate when the answer is both "yes" and "no" at the same time, which is impossible.
If you use the short circuit or/and (|| and &&) the system doesn't evaluate the entire expression if it doesn't have to. So if the user enters "no", the first part that checks if it is not "yes" evaluates to true. Since an or condition only needs one true to evaluate to true it doesn't evaluate anything else and just returns.
You need && because you are saying if the answer is not yes and is not no ask for input again. Here is more on short circuit boolean operators: https://users.drew.edu/bburd/JavaForDummies4/ShortCircuitEval.pdf.
Related
int option=0;
while (option1!=1 || option1!=2){
System.out.println("Give 1 for the first list which includes what we have in our exhibition");
System.out.print("and 2 which we have not:"); // 2 print because i want to show at two different lines
option1= Integer.parseInt(in.nextLine());} // when i give 1 or 2 as an option it doesn't goes out frome the loop
This is an infinite loop:
while(option1!=1 || option1!=2)
Since option1 can never simultaneously equal both 1 and 2, then this condition will always evaluate to true and the loop will always continue. You probably meant to use the logical "and" operator (&&) in your comparison:
while(option1!=1 && option1!=2)
That way the loop will end if option1 ever equals one of those two options.
You need to say option1!=1 && option1!=2, not option1!=1 || option1!=2
Please remember to format your code so it's readable. Just add four spaces in front of each line.
I am trying to make a control that will block the user from entering a term year for their home loan that is over 30.
HomeLoan hLoan=new HomeLoan(name, custID, loanID);
System.out.println("You selected Home Loan");
System.out.println("Enter term: ");
term=input.nextInt();
boolean l=false;
boolean s = hLoan.termCorrect(term);
System.out.println(s);
if (s=true){
System.out.println("Error: Maximum of 30 years");}
else {l=false;}
It calls a method that termCorrect() that determines if the term is over 30, and returns true or false. When I run it, the value of s is correct for the input that I use, but it always run the error message for some reason, regardless of s.
Any help would be greatly appreciated.
You are using the assignment operator =:
if (s=true){
Use the comparison operator == instead:
if (s == true) {
or, because it's already a boolean, use s itself:
if (s)
The last form is preferable. It's concise, and there's no chance to an operator confused with =.
Assignment operator in if statement is invalid. Change from
if (s=true){// this invalid
To
if (s){
= is assignment. == is equality comparison.
Your if statement is incorrect. By using s=true you are setting s to true inside the if. The equality operator in Java is ==. Therefore, you could do this:
if(s==true)
Or, since s==true is logically equivalent to s (think about it), you can do this:
if(s)
i am having trouble validating this part of my code ,the error message is not diplaying correctly and if i only hit the enter key the program will exit, any help is appreciated.
strInput1="";
strInput1 = JOptionPane.showInputDialog(null,
"2013 SHIPPING OPTIONS\n\n(O)vernight shipping-$10.00"+
"\n(T)wo-Day shipping-$7.50\n(P)riority shipping-$5.00"+
"\n(N)o cost shipping"+
"\n\nPlease select a shipping option(O,P,T or N) ",
"Wiliam's Party Store",3);
if(!strInput1.equals(""))
JOptionPane.showMessageDialog(null,
"You MUST enter O,o,T,t,P,p,N,n",
"ERROR!!!",0);
cShipping=(strInput1.toUpperCase().charAt(0));
while((!strInput1.equals(""))&& !(cShipping=='P')|(cShipping=='T')||(cShipping=='O'))
{
JOptionPane.showMessageDialog(null,
"You MUST enter O,o,T,t,P,p,N,n",
"ERROR!!!",0);
strInput1 = JOptionPane.showInputDialog(null,
"2013 SHIPPING OPTIONS\n\n(O)vernight shipping-$10.00"+
"\n(T)wo-Day shipping-$7.50\n(P)riority shipping-$5.00"+
"\n(N)o cost shipping"+
"\n\nPlease select a shipping option(O,P,T or N) ",
"Wiliam's Party Store",3);
if (!strInput1.equals(""))
cShipping=(strInput1.toUpperCase().charAt(0));
strInput1 = "N";
}
PO1.setShipping(cShipping);
For multiple negative expressions use the logical && operator:
while (!strInput1.equals("") && cShipping != 'P' &&
cShipping != 'T' && cShipping != 'O')
The || operator short circuits expressions so the while loop can remain active even if strInput1 is empty. Also cShipping is never assigned in the second while loop which will prevent the loop from exiting.
Aside: A do-while loop could allow both loops to be merged into one.
You have a single | in your code which is a Bitewise Or and not a logical or ||
So your trouble is validating your code, and not the code itself? I know our first instinct is too rush in and correct your code however I would like to offer an alternative solution I think is more beneficial.
I think the solution to your troubles would be to refactor your code, first learning good coding practice and styles. This would help you in the future as well with any development work.
A good place to start would be here (wikipedia) where they discuss coding conventions and refactoring.
In the code you pasted I see spelling mistakes, a line saying ' enter code here`' and flaws in your logic. Among other things, it is also not clear where your last 'if' statement includes the second line: and while the indent shows that it may, the lack of braces ensures otherwise.
if (!strInput1.equals(""))
cShipping=(strInput1.toUpperCase().charAt(0));
strInput1 = "N";
should be the following.. (if this is what you indeed intended)
if (!strInput1.equals(""))
cShipping=(strInput1.toUpperCase().charAt(0));
strInput1 = "N";
On a side note it would be worth improving on your code by using modularisation, coupling and perhaps even more error checking/catching.
I am confused about how && operator is working
if (StringUtils.isNotEmpty(cartModification.getStatusCode())
&& (cartModification.getStatusCode().equalsIgnoreCase(UNFCommerceCartModificationStatus.Sell_Out)))
Above statement is coming as true
while
if (StringUtils.isNotEmpty(cartModification.getStatusCode())
&& cartModification.getStatusCode().equalsIgnoreCase(UNFCommerceCartModificationStatus.Sell_Out))
is evluaated as false.Only difference between the 2 statements are braces.
As an additional input i have checked it with debugger and
StringUtils.isNotEmpty(cartModification.getStatusCode() =true
cartModification.getStatusCode().equalsIgnoreCase(UNFCommerceCartModificationStatus.Sell_Out)=true
I just added extra parenthesis in the second part and it was evaluated as true, Data is same as i have pointed out in question.
Since the commentbox isn't really approriate for this one:
How about trying this in a single run.
if(StringUtils.isNotEmpty(cartModification.getStatusCode())
&& cartModification.getStatusCode().equalsIgnoreCase(UNFCommerceCartModificationStatus.Sell_Out))
System.out.println("First try is true");
if(StringUtils.isNotEmpty(cartModification.getStatusCode())
&& (cartModification.getStatusCode().equalsIgnoreCase(UNFCommerceCartModificationStatus.Sell_Out)))
System.out.println("Second try is true");
No matter what, you should either get no or two lines (since both statements are the same).
Note it's possible that just one line is printed, this means that any call on getStatusCode() invokes a change on any value used in at least one of the conditions.
am having trouble trying to validate a user response to exit my app or try again(its a simple game)? when the game finishes I ask the user if they want to continue type "y" for yes or "n" for no to exit. How can I validate their response so if its neither y or n I show an error message and ask them to type it again???
This doesn't seem to worK for me???
if (!choice.equalsIgnoreCase("n") && !choice.equalsIgnoreCase("y"))
System.out.println("Error enter y for yes and n for no");
System.out.println("Would you like to play again (y/n):");
choice = sc.next();
Just change the
if (!choice.equalsIgnoreCase("n") && !choice.equalsIgnoreCase("y"))
to
while (!choice.equalsIgnoreCase("n") && !choice.equalsIgnoreCase("y"))
This will continue to ask them for another letter each time they don't choose the letter 'n' or 'y'.
EDIT: Also, you might want brackets around the code within the if (soon to be while) statement.
Without any full context, difficult to give a relevant answer.
But you can already test your code with curly braces around the if statement:
if (!choice.equalsIgnoreCase("n") && !choice.equalsIgnoreCase("y")){
System.out.println("Error enter y for yes and n for no");
System.out.println("Would you like to play again (y/n):");
choice = sc.next();
}
Indeed, with your current code, only the first line:
System.out.println("Error enter y for yes and n for no");
is taken in account by your condition.