I am having trouble with my do-while statement. I created a do-while loop to ensure the only accepted input is "e" or "o" (not case sensitive), however, it continues the loop even though I inserted the desired input. Any help is appreciated!
Current Code & Result
This statement:
while(!side.equalsIgnoreCase("O") || !side.equalsIgnoreCase("E"));
is always true
If you input E or e, this !side.equalsIgnoreCase("E") is false but this !side.equalsIgnoreCase("O") is true
If you input O or o, this !side.equalsIgnoreCase("O") is false but this !side.equalsIgnoreCase("E") is true
Since you are using ||, true || false gives you true so the loop never ends
For every other input, both are true (true || true) which is also true
You need to replace it with:
while(!side.equalsIgnoreCase("O") && !side.equalsIgnoreCase("E"));
Related
String groupType="local";
if(groupType==null ||groupType.equals("")||!groupType.equalsIgnoreCase("local")||!groupType.equalsIgnoreCase("global")||!groupType.equalsIgnoreCase("universal")){
System.out.print("evlauate to true ");
}
Why does this code evaluate to true, !groupType.equalsIgnoreCase("local") should set it to false ,
Even if you reduce the condition to
if (!groupType.equalsIgnoreCase("local")||!groupType.equalsIgnoreCase("global"))
It will always be true, since groupType can't be equal to both "local" and "global" at the same time.
You probably want to use && (AND) instead of || (OR).
if (groupType == null || groupType.equals("") ||
(!groupType.equalsIgnoreCase("local") && !groupType.equalsIgnoreCase("global") && !groupType.equalsIgnoreCase("universal"))) {
System.out.print("evaluate to true ");
}
Now it will evaluate to true if groupType is either null or empty or isn't equal to one of the values "local"/"global"/"universal". I'm assuming that's what you wanted.
Let's look at each of the operands of the || operator:
the string is equal to null? False.
the string is empty? False.
the string is not equal to "local"? False.
the string is not equal to "global"? True.
the string is not equal to "universal"? True.
Two of the conditions evaluate to true. Therefore, the whole if statement evaluates to true.
maybe you wanted this:
if(groupType==null ||groupType.equals("")
||!(groupType.equalsIgnoreCase("local")
||groupType.equalsIgnoreCase("global")
||groupType.equalsIgnoreCase("universal")
)
)
I cannot for the life of me figure out why this code loops indefinitely when "turnOrder" is set to "first." It seems to be something about the "or" operator in the "do while loop." But I have no idea how to properly format it.
String turnOrder;
do {
Scanner to = new Scanner(System.in);
turnOrder = to.nextLine();
if ((!"first".equalsIgnoreCase(turnOrder)) || (!"second".equalsIgnoreCase(turnOrder))) {
System.out.println("Type your answer as 'first' or 'second.' Without the punctuation.");
} else {}
} while ((!"first".equalsIgnoreCase(turnOrder)) || (!"second".equalsIgnoreCase(turnOrder)));
It loops cause when you type "first", it returns false in
!"first".equalsIgnoreCase(turnOrder), BUT
it return true in
!"second".equalsIgnoreCase(turnOrder))
false OR true = true, so it will keep looping
You should always reduce your logic operations to their simplest form.
"((!"first".equalsIgnoreCase(turnOrder)) || (!"second".equalsIgnoreCase(turnOrder)))"
can be simplified using De Morgan's Laws to
!("first".equalsIgnoreCase(turnOrder) && "second".equalsIgnoreCase(turnOrder))
Of course turnOrder cannot be "first" and "second" simultaneously. It will always evaluate to true, thus your while loop will loop indefinitely.
while ((!"first".equalsIgnoreCase(turnOrder)) || (!"second".equalsIgnoreCase(turnOrder)))
This statement will always be true until you come up with a turnOrder value that equalsIgnoreCase-s to "first" and "second" simultaneously. Good luck with that! Perhaps you meant...
while (
!(
"first".equalsIgnoreCase(turnOrder) ||
"second".equalsIgnoreCase(turnOrder)
)
)
I created a simple do while loop where I want to check a condition ( that the number of characters will be 2 and that both of the characters will be equal).
For some reason if I use the loop with || operator it works and if I use the loop with && operator it doesn't work.
I found it hard to understand why the condition works with || and not with &&.
Any idea?
String check;
do {
int num = (int)(Math.random()*200)+10;
System.out.println(num);
check = String.valueOf(num);
} while (check.charAt(0) != check.charAt(1) || check.length() != 2 );
Probably you've missed to apply a negation somewhere.
If you want to convert your ||-based expression to a &&-based expression, then you'll have to do:
while (!(check.length() == 2 && check.charAt(0) == check.charAt(1)));
Note that, in order to avoid an ArrayIndexOutOfBoundsException, I'm switching the pieces of the expression, so that we first check the size of the String, after which we test the first two characters for equality.
Your condition for stopping is length is 2 and both characters are equals.
That means: stop when (check.length() == 2 && check.charAt(0) == check.charAt(1)) Note that it's always better to first check the length since && is a short-circuit operator and otherwise if check's length is smaller than 2, you'll get an exception.
Now, since the condition for the do-while loop is for when to continue looping, you want to negate that (tell the loop when to continue, not when to stop). So you want: !(check.length() == 2 && check.charAt(0) == check.charAt(1)).
You can leave it at that, or you can use De-Morgan's law and convert it to a ||-expression: !(A && B) =~ !A || !B so for your condition that would be !(check.length == 2) || !(check.charAt(0) == check.charAt(1)) which is equivalent for check.length != 2 || check.charAt(0) != check.chatAt(1), which is the condition you wrote that works. Since all transitions are iff (if and only if), you can see the equivalent to your || condition.
If you use an AND condition (i.e. while (check.charAt(0) != check.charAt(1) && check.length() != 2 )) the loop will exit if either condition fails. Both the first AND second conditions must be true for the loop to continue. So if you hit a 2-digit number the loop will exit even if the first two characters match. Similarly if you get a 3 digit number where the first two digits match, the loop will exit. Is this the intended logic?
I'm new to Java as of the past day or two and I've been messing around making some very basic programs. I have the following code as a simple number guessing program
public class GUESS2 {
public static void main(String args[])
throws java.io.IOException {
//This program will have you solve a numeric puzzle using different hints as you get closer
int answer='5', guess=0, i=0;
char ignore;
do{
i++;
System.out.print("Can you guess the number I'm thinking of???");
guess = (int) System.in.read();
if(guess==answer) System.out.println("CORRECT!!!");
if(guess >answer) System.out.println("Too high!");
if(guess <answer) System.out.println("Too low!");
do{
ignore=(char) System.in.read();
}while (ignore != '\n');
} while(answer!=guess && i != 5);
}
}
My issue here is with the "while" statment. I want it to exit this loop when EITHER answer=guess or i=5. When I use | or || it gives me the opposite and ONLY exits when I do answer=guess and i=5 at the same time which seems backwards to me.This current code using "&&" works when EITHER answer=guess or i=5 which doesn't make sense to me.
Again I'm a beginner and I appreciate you guys taking the time to help me- probably something simple but I've messed with it for a while.
Let's consider the possibilities. First, with OR(||) operator:
(answer != guess || i != 5)
If answer is equal to the guess, answer != guess evaluates to false, which, based in what you described, should make the program exit. However, i != 5 will still be true, so the whole statement will evaluate to true, making the program keep going, while the statement is true.
If answer is equal to the guess, and i == 5, both will evaluate to false, and, as none of them are true, the OR will evaluate to false, making the loop exit.
Now, with AND(&&) operator:
(answer != guess && i != 5)
If answer is equal to the guess, answer != guess evaluates to false, and, as it is an AND operator, which requires both to be true, the statement will evaluate to false, making the loop exit. If i is equal to 5, i != 5 evaluates to false, and, as already said, will make the statement evaluate to false, and the loop exit.
Hope to have helped.
EDIT: A link I found, may help you, see the 8th item.
If you want to exit the loop when either A or B is true, then you want to stay as long as this isn't the case: when both A and B are false. Which is just how your code reads.
The && gives you the behaviour you want because it requires both of those conditions to evaluate to true in order to continue. This means that if answer equals guess (the first conditions fails), or i equals five (the second condition fails), the loop will exit. However, with the || operator, you're saying continue on as long as either one of these is true. They're known as logical and and logical or, respectively. This should help:
a && b -> if both are true, evaluates to true, otherwise false
a || b -> if either are true, evaluates to true, otherwise false
it does not make sense because you did not read the things in a right way:
What you are asking for is: keep on looping until either answer == guess OR i ==5
However, this piece of code actually means:
do{
} while(answer!=guess && i != 5);
"keep on looping if both answer is not guess and i != 5"
which essentially mean the same thing. The reason you find it counter-intuitive is because you are thinking of the "stopping condition" while do-while loop is specifying the "continuation condition"
Some languages (not Java) do provide do-until loop, which is doing what you want. It may look like this if it is provided in Java:
do {
} until (answer == guess || i == 5)
Suppose we use and operator such that
if (a.enable() && b.enable())
so the above statements indicates that both the statements need to be true to proceed
What about the case if a.enable() return false, and if we write the statement such that
if (a.enable() && (b.enable() || c.enable()))
so this above statement means that a.enable() needs to be true and from the second part either b.enable() or c.enable() needs to be true. Either one of them needs to be true to proceed, but if a.enable() is not true then the condition fails without any further checks.
Is this correct?
Yes, && means AND, and || means OR. And they're both short-circuit, so in the following case:
if (a.enable() && b.enable())
b.enable() would not even be called if a.enable() returns false.
And in the following case:
if (a.enable() || b.enable())
b.enable() would not even be called af a.enable() returns true.
That's what allows conditions like
if (s != null && s.equals(foo))
which would cause a NullPointerException if the operator wasn't short-circuit.
if (a.enable() && b.enable())
The 2nd condition will be called only if the 1st condition is true.