check for a condition in a do loop in java - java

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?

Related

Java If block with multiple statements

I have a question about IF clause in Java.
I have and expression:
if ((someObject != null & connectedToTheInternet) || operate) {
// some action
}
Is my logic right: if someObject != null equals to true and connectedToTheInternet equals false then we have (someObject != null & connectedToTheInternet) equals false and then we have the following block:
if (false || operate) {
// some action
}
And if operate equals true then // some action will be triggered?
Just a first note: logical AND operator is "&&" and not just "&" (bitwise AND).
Following, your answer is YES... JVM will run conditions following your thinking.
By the way, I suggest you to read something abot short-circuit of these operators: it can be interesting if you are learning.
For example if you have if (a && (b || c) and a==false, then JVM won't evaluate b or c conditions because false && ... will be always false.
The same in the case of if (a || b || c && d): if a==true then JVM will ignore the other parts and consider it as true because true || .... will be always true.
Yes. if-clauses are evaluated from left to right. If no parenthesis are used, && has precedence, even higher precedence has ! (not) - similar to multiplication (AND), addition (OR) and negative numbers (-) in math (e.g. "A && (B || C) != A && B || C == (A && B) ||C") - I recommend to use parenthesis if you are unsure. This makes it possible to combine != null checks and calls to methods in the same if statement (e.g., if (object!=null && object.dosomething())).
Btw. there is a difference between & and && (short-circuit), when & is used, the second condition gets evaluated even if the first is false already. When && is used, Java doesn't check the second condition if the first one is false as the whole term cannot be true anymore - this is only important when the second condition is not a boolean variable but a method (which gets called or not -> side effects; this "skipping" is called short-circuit). Same for || and | where the second operator might not get evaluated if the first is already true (in case of ||).
Normally only ||and && are used.
Just for completeness: & is also the bitwise AND operator in Java.
if (false || operate) {
// some action
}
If operate true then if block executing.

Do while loop comparing Strings

I'm trying to do a "do while" loop with a nested if statement. I'm trying to compare two possible values for a String variable "word". If !word.equals "deeppan or thin" do something, else do something. But its not liking me using the or || comparator .. Any suggestions would be welcome.
do {
word = scan.next();
if ( !word.equalsIgnoreCase( "Deeppan" || "thin" ) ) {
System.out.print("Sorry you must specify a Deeppan or thin base, try again: ");
} else {
break;
}
} while ( true );
equalsIgnoreCase takes a single string argument, not a logical expression. You can combine them with || or && though:
if (!word.equalsIgnoreCase( "Deeppan") && !word.equalsIgnoreCase("thin" ))
You have to do it like this:
if (!word.equalsIgnoreCase("Deeppan") && !word.equalsIgnoreCase("thin")) {
Think about the || which i switched to &&, because the if should only be true, if the value is not the first AND not the second one!
This part is wrong, that's not how you use the boolean || operator, and anyway the logic is incorrect:
if (!word.equalsIgnoreCase("Deeppan" || "thin"))
It should be like this, comparison-operator-comparison, and notice the correct way to state the comparison for the effect you want to achieve:
if (!(word.equalsIgnoreCase("Deeppan") || word.equalsIgnoreCase("thin")))
Or equivalently, using De Morgan's laws (and easier to read and understand, IMHO):
if (!word.equalsIgnoreCase("Deeppan") && !word.equalsIgnoreCase("thin"))
You have a few issues going on. First:
"Deeppan" || "thin"
is attempting to use the boolean "OR" operator to compare two strings. The "OR" operator can only compare boolean results and returns a boolean that is the result of the comparison:
System.currentTimeMillis() == 123455667 || object.equals(this) // both sides are boolean results.
true || false // returns 'false'
But let's pretend for a second that "Deeppan" || "thin" is OK (remember, it isn't) and the compiler knows that you want to compare the two strings. It still leaves the issue that the OR operator returns a boolean result (true or false), which you are then attempting to pass into the method equalsIgnoreCase on the word variable. equalsIgnoreCase takes a String argument, not a boolean. This is the second compilation issue. As has been pointed out, what you need is to check for the conditions separately and OR the result to get the final boolean
if("Deeppan".equalsIgnoreCase(word) || "thin".equalsIgnoreCase(word)) {
// do something
}
("Deeppan" || "thin")
is a boolean expression. equalisIgnoreCase takes a string. Therefore you need to make two seperate calls and OR the (boolean) results

How to use 'or' in Java?

I'm quite new to Java, and can't figure out how to use 'or'. What is the Java equivalent?
I've already tried && and || but eclipse does not recognise it.
This is part of my code:
if (action.equals ("run") || ("sprint")) {
System.out.println("you ran");
}
else {
System.out.println("else");
}
I've already tried && and || but eclipse does not recognise it.
That's very strange, but just to cover the basics: Let's assume you have the variable a and it contains the value 5. Then:
if (a == 5 || a == 7)
...will be true, because the first part of the expression (a == 5) is true. So the statement "a equals 5 or a equals 7" is true.
The || operator can only be used, in Java, where a boolean (true or false) expression is expected, such as in an if statement like the above. So pretty much in an if or a conditional operator (that ?...: thing, sometimes called the ternary operator).
Re your edit, the problem is that both sides of your || operator aren't true or false ("boolean") expressions. Your statement:
if (action.equals ("run") || ("sprint")){
breaks down like this:
if (
action.equals ("run")
|| // ("or")
("sprint")
)
the second part of that isn't a true/false, it's a string. The correct way to express that in Java (or nearly any other programming language) is:
if (action.equals ("run") || action.equals ("sprint")){
Now both sides of the || result in true/false exprssions:
if (
action.equals ("run")
|| // ("or")
action.equals ("sprint")
)
The reason for this is that the second part may have nothing whatsoever to do with action, and so the compiler can't assume you mean to re-use it in the second part of the expression. You might, for instance, want to use || with two completely unrelated things:
if (action.equals("run") || somethingElse.equals("run")) {
Ok. ("sprint") is not a Boolean expression. Since a if condition expects a Boolean expression your code returns an error. You should change the line with:
if (action.equals ("run") || action.equals("sprint")){
The equals method returns a boolean and the || operator wants two booleans on each side.
You're doing an action.equals("run") on one side but then a ("sprint") on the other which isn't a boolean expression.
Change your code like so:
if (action.equals("run") || action.equals("sprint")){

Why won't my code compile which checks if a string begins with vowel?

if (flipped.charAt(0) = "a" || "e" || "i" || "o" || "u"){
paren = "(" + flipped;
String firstpart = paren.substring(0,5);
String rest = paren.substring(5);
System.out.println(rest+firstpart);
}
In this code, I'm looking to check if the first character of String flipped is a vowel. If it is, I'm adding a parenthesis to the beginning and moving the first 5 characters to the end of the string. Eclipse is giving me java.lang.NullPointerException and saying that "The left-hand side of an assignment must be a variable." What can I do to fix this?
Your code has following issues,
Use conditional operator == instead of assignment = at if statement.
Use single quotation ' instead of double " for char
Make a separate method for vowel check.
boolean isVowel(char ch){
ch=Character.toLowerCase(ch);
return ch=='a' || ch=='e' || ch=='i' || ch=='o' || ch=='u';
}
Another very simple solution I often use:
if ("aeiou".indexOf(Character.toLowerCase(text.charAt(0))) >= 0) {
// text starts with vocal.
}
You can also use regular expression matching:
if (text.matches("^[aeiou].*")) {
Use a collection that holds all of these values.
Set<Character> myList = new HashSet<Character>(Arrays.asList('a', 'e', 'i', 'o', 'u'));
if(myList.contains(Character.toLowerCase(flipped.charAt(0)))) {
// Do work
}
This line of code (while wrong: = will assign, == will compare)
if (flipped.charAt(0) == "a" || "e" || "i" || "o" || "u"){
will first compare flipped.charAt(0) == "a" which returns a boolean. Then it will continue with boolean || "e" || "i" || "o" || "u".
boolean || "e" is not valid code.
The accepted answer although explained the problem didn't quite show the solution for how he was checking the problem. So I figured i'd show a corrected solution as well as offer my own solution to such a problem.
Someone who cannot understand Boolean compare syntax isn't going to understand All those special classes. Not to mention some of those needs imports he may not have and will now need to understand why he's getting errors. I assume this person has came to a resolution by now given it's been 5 years.. but in the evnet someone else or even this person still is unsure on something.
Your Original Code Updated ( I removed the contents inside as I don't know what they do or if they were accurate ).
char c = flipped.charAt(0);
if (c == 'a' || c == 'A' || c == 'e' || c == 'E' || c == 'i' ||
c == 'I' || c == 'o' || c == 'O' || c == 'U' || c == 'u')
{
Now this supports checking if "flipped.charAt(0)" equals a vowel weather lower case or uppercase. As you can see we do a Boolean check for each situation by checking if "C" equals something else. You only offered the check one time so the syntax error was because of that you were doing Boolean checks on non Boolean values. When you have values next to "||" it must be "false", "true" or "SomethingA == SomethingB". If that something is an object you typically have to do "SomethingA.equals(SomethingB); E.g. byte,int,short,long,float,double will all work just fine, but String would require the second method.
Below are some tips to reduce this further.
We can force char "c" to lowercase by doing any of the below methods.
char c = Character.toLowerCase(flipped.charAt(0));
Or we can do a more clever way.
char c = flipped.charAt(0) | 32;
As such now we only need to do the following to check if it's a vowel.
char c = flipped.charAt(0) | 32;
if (c == 'a' || c == 'e' || c == 'i' || c == 'o' ||c == 'u')
{
However we can take this a step further.
We can reduce the code even more!
if (((1 << flipping.charAt(0)) & 2130466) != 0)
{
So basically how my final solution works. Unfortunately it's pretty involved to explain it, but i'll try my best.
In any programming language you have values of Byte, Short, Int, and Long these are 8bit, 16bit, 32bit, and 64bit respectively.
When you perform 1 << N you are doing 2^N which is basically the power of two method. The thing is though when you use this on the Byte, Short, Int, or Long the value "N" is reduced.
So.. (keep in mind different languages handle these differently).
Byte can only range from 0-7.
Short can only range from 0-15.
Int can only range from 0-31.
Long can only range from 0-63.
So now we know letters have a value A-Z = 65-90 and a-z = 97-122 when we do 1 << letter it will actually be 1 << (1-26) because the those numbers module or remainder of 32 is 1-26 in both cases.
You can see this by doing the following.
A = 65.
65-32=33.
33-32=1. Stop.
So now we know A will equal 1 in this situation.
So now we do 1 << 1 or 2^1 = 2. So the letter A gives us the value "2".
Repeat this for all the vowels and we can a sum of bit values. Bit values are just powers of two added together. I again really can't go hard explaining this it's pretty involved but hopefully you kind of have an idea.
Now what we are doing is taking the sum of the vowel bits and comparing it to the number 2130466 which contains the bit values of A,E,I,O,U already. If those bit value we check for happens to exist in 2130466 then it must be A,E,I,O,U and as such it's a vowel.
The return result is 0 or the value so we simply check that this value doesn't equal 0.
Please keep in mind if anyone uses this that this assume you know the letter will be A-Za-z situation because if it was for example a "!" this will return a false positive as a "A" vowel. You can solve this by prechecking if the value is below "A" and above "u" and return out early.

error: bad operand types for binary operator '||'

This is my statement
while(coord.getRow() || coord.getColumn() != 0)
I basically want it to loop while the x coordinate and y coordinates are not 0. then stop executing when either equals 0. Both the row and column of the object cord are ints.
Like the title I'm receiving the error:
error: bad operand types for binary operator '||'
I could I go about executing a while loop to do something like this?
while(coord.getRow() != 0 && coord.getColumn() != 0)
instead of
while(coord.getRow() || coord.getColumn() != 0)
Try:
while((coord.getRow() != 0) && (coord.getColumn() != 0)) {
// etc...
}
You have to use && here instead of ||, because you want to stop when either equals 0, so in your while case you have to make sure both are not zero.
The reason for the error is that logical operators like || and && in Java expect logical expressions. In other words, something that can evaluate to true or false.
Since your functions return integers, these are not logically valid. Whereas, something like coord.getRow() != 0 is either true or false depending on what coord.getRow() is.
use:
while(coord.getRow() != 0 && coord.getColumn() != 0)
use && (and) operator instead of || (or).
&& is true if both true on the other hand || is true if any one is true.

Categories