How can I make this stopping criteria effective? - java

I dont know why this stopping criteria keeps failing but I believe it has something to do with the logical or (||). I debugged and it doesnt seem to stop where I want it to, which is on when cp (current position) is on the perimeter of the array.
if(cp == start || (cp.getColumn() > 0 || cp.getColumn() < maze[0].length-1 || cp.getRow() > 0 || cp.getRow() < maze.length+1)){`
This is a for a maze solving algorithm. Basically, the maze is a 2D array made up of X's for walls. Every cell with an X is a wall and the 'current position' can not access it. The mission of the 'current position' is to get to out of the maze which means it either has to be in the first or last column or first of last row. The algorithm works very well but just doesn't recognize when the current position is at the index of the exit.
I'm sorry for being so vague, I've been working on this for so long...

So, none of the following things is true:
cp == start
cp.getColumn() > 0
cp.getColumn() < maze[0].length - 1
cp.getRow() > 0
cp.getRow() < maze.length + 1
But you think (at least) one of them should be true. Which one?

Being or statements, that extra set of parentheses are redundant:
if(cp == start || cp.getColumn() > 0 || cp.getColumn() < maze[0].length-1 || cp.getRow() > 0 || cp.getRow() < maze.length+1){
I can't see exactly what you are doing, but I hope this helps at least...

I con't really see what you're trying to do here, but guessing that 'maze' is a two dimensional array, it should probably be maze.length-1 in the last comparison. However, this would make the if statement evaluate to true when cp is NOT on the perimeter of the array.

It appears you are using the start conditions in your OR set. You may want to put an ! (Not) before the first bracket. As written, I think the else clause would be where your stop should occur.
Consider wrapping the processing code in this if statement.
Desk check your logic to see when you exit. Remember that OR stops processing on the first TRUE, and AND stop processing on the first FALSE.

I'm not sure you've copied your code correctly
if(cp == start
|| (cp.getColumn() > 0 || cp.getColumn() < maze[0].length-1
|| cp.getRow() > 0 || cp.getRow() < maze.length+1)) {
For simplicity of understanding pretend that maze.length[0]-1 evaluates to, say 3, then consider this bit:
cp.getColumn() > 0 || cp.getColumn() < 3
That will be true for every value of the cp.getColumn(), try say 8, yep, bigger than 0, -99, yep it's less than 3. I'll bet you meant
cp.getColumn() > 0 && cp.getColumn() < 3
this will be true if the column is in the maze. If you want to test for out of the maze:
cp.getColumn() <= 0 || cp.getColumn() >= 3
(Side note I use <= 3, not just == 3 deliberately, this deals with cases such as move of more than one step.)
If you want to test if it's in the maze you have
if(cp == start
|| (
cp.getColumn() > 0 && cp.getColumn() < columnCount
&& cp.getRow() > 0 && cp.getRow() < rowCount)) {
if you want to test if it's outside the maze
if(cp != start
&& (
cp.getColumn() <= 0 || cp.getColumn() >= columnCount
|| cp.getRow() <= 0 || cp.getRow() >= rowCount)) {

Related

Java while(condition doesn't reach)?? Why

Why is it when I do this
while(word.charAt(left) == word.charAt(right) && left >= 0 && right < word.length()){
left--;
right++;
}
its says in the while conditions "left >= 0 && right < word.length()" condition doesn't reach, but when I do it like this
while(left >= 0 && right < word.length() && word.charAt(left) == word.charAt(right)){
left--;
right++;
}
The conditions are met.
Is there an order for while(loop conditions)???
The order does matter as conditions are checked from left to right. You're getting that message because if the previous condition evaluates to true, then those two conditions
left >= 0 && right < word.length()
will always evaluate to true. You probably want the latter (since you would want to check all the conditions).

Why is the inverted if-statement false? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 5 years ago.
Improve this question
Why does the if-statement count as false?
int money = -342;
int reviews 3;
if (!(money > 0 || reviews < 5 || reviews > 0)){}
Money is false,
the both reviews are true
and inverting them results with a true for the money,
and two falses for both of the reviews.
As I am using || for ´or´, one true should be enough to make the whole of-statement become true.
Your if test always evaluates to false because regardless of the value of Reviews, either Reviews < 5 or Reviews > 0 will be true and you are then negating the result. (The value of Money is irrelevant, since || evaluates to true if either operand is true.) I think what you want is for these three to be true:
Money must be greater than 0
Reviews must be between 0 and 5 (inclusive)
This if test will do the job:
if (Money <= 0 || Reviews > 5 || Reviews < 0) {
System.out.println("Something went wrong");
} else {
System.out.println("We're good");
}
Alternatively, you can test for the positive conditions:
if (Money > 0 && Reviews >= 0 && Reviews <= 5) {
System.out.println("We're good");
} else {
System.out.println("Something went wrong");
}
Because the following:
if (!(Money > 0 || Reviews < 5 || Reviews > 0))
evaluates to
if (!(True))
thus, inverted,
if (False)
The negation symbol is negating the entire statement. Thus, if any of those conditionals are true then false is returned. If all conditionals are false then true is returned.
if (!(Money > 0)){...} - It says Something went wrong as the Money integer is below 0. - No, it says it's below or equal to 0.
(Money > 0 || Reviews < 5 || Reviews > 0) - this is true if at least one of parts between || is true, but:
!(Money > 0 || Reviews < 5 || Reviews > 0) - this is false if at least one of parts between || is true. You get an opposite result with ! (negation).
Why your value is false
Money is less than zero. That is false.
Reviews is less than 5. That is true.
It then short-circuits, but if you continued, Reviews is greater than 0. That is true.
Regardless, the whole statement in the brackets evaluates to true because of how an or operator works. You then invert it, so it turns into false.
A solution?
Honestly, it seems that what you want is a check that money is greater than 0, that reviews is less than 5 and that reviews is greater than 0.
This means that you should probably have something like money > 0 && reviews <= 5 && reviews >= 0. I assume that reviews here is something like a 0-5 star range. Obviously, if it were 1 to 5, that would be different.
!(Money > 0) == (Money <= 0)
!(Money > 0 || Reviews < 5 || Reviews > 0) == (Money <= 0 && Reviews >= 5 && Reviews <= 0)
It is better not to use ! before the whole statement.
Thats because it is satisfying the Reviews < 5 and Reviews > 0 to true.
So the if statement in if (!(Money > 0 || Reviews < 5 || Reviews > 0)) will be false because you are using not operator.Thats the reason it prints We´re good.
Umm. wait I've been doing this for a few years now and I'm pretty sure that the "!" also applys to the "||" thus making it an "&&" meaning it will always be false.
The parentheses take precedence.
Take a look at the condition:
(!(money > 0 || reviews < 5 || reviews > 0))
First, the part inside the inner parenthesis are evaluated:
money > 0 || reviews < 5 || reviews > 0
Then, the order is from left to right:
money > 0 is false, continue to next;
reviews < 5 is true, so the expression in the inner parentheses is true.
The expression within the inner parentheses evaluates to true, so effectively your condition is equal to !(true) and that makes (false).
I suggest you study the basics of expression evaluation and operator precedence. Also, as pointed out by Ted Hopp, you need to rethink your logic. For example, I would rewrite expressions like !(money > 0) to money <= 0, to simplify it. In my opinion, it's best to not use the negation operator (!) in conjunction with relational operators (like < or ==), unless you absolutely have to.
Note:
The && and || operators perform Conditional-AND and Conditional-OR operations on two boolean expressions. These operators exhibit "short-circuiting" behavior, which means that the second operand is evaluated only if needed.
Let's understand your code conditions step by step:
int Money = -356;
double Reviews = 4.8;
if (!(Money > 0 || Reviews < 5 || Reviews > 0)) {
System.out.println("Something went wrong");
} else{
System.out.println("We´re good");
}
Given :
Money = -356
Reviews = 4.8
Let's break and evaluate the inner if condition first:
(Money > 0 || Reviews < 5 || Reviews > 0)
1. Money > 0 -356 > 0 **False**
2. Reviews < 5 4.8 < 5 **True**
3. Reviews > 0 4.8 > 0 **True**
Now as we can see inner conditions evaluate True but if you notice there is a (logical not) " ! " operator added outside.
(!(Money > 0 || Reviews < 5 || Reviews > 0))
Called Logical NOT Operator. Use to reverses the logical state of its
operand. If a condition is true then Logical NOT operator will make
false.
Hence when your inner condition is True the Logical not ! makes it False.
So, System.out.println("We´re good"); Is executed.

basic if statement, operator <= undefined

I'm new to programming
if( (N%2==0) && (6<=N<=20) )
Throws the error below
The operator <= is undefined for the argument type(s) boolean, int
Please help me fix it.
You can't compound the statement like that. You need to && it.
For example,
if ((N % 2 == 0) && (6 <= N && N <= 20)) {...}
The reason you get the error is the first condition of 6 <= N resolves to a boolean and you then attempt to check if a boolean is <= to an int. That does not compute.
You can't compare 2 conditions in one check, you need to split it to two checks
if (N % 2 == 0 && N >= 6 && N <= 20)
You should separate the conditions with logical operators (&& in this case):
if (N % 2 == 0 && N>=6 && N <= 20)

If-else statements, always running

I am working on making a coffee ordering system. It takes inputs from users and calculates the price of their coffee. One of the inputs asked for is "syrupshots". This code always makes syrupshots = 3 even if the user properly chose a number according to the size of their coffee.
//if size == tall syrup shots <=3
if(size == 1 && syrupshots < 1 || syrupshots > 3)
{
syrupshots = 3;
}
//else if size == medium syrup shots <=5
else if(size == 2 && syrupshots < 1 || syrupshots > 5)
{
syrupshots = 3;
}
//else if size == Venti syrup shots <=7
else if(size == 3 && syrupshots < 1 || syrupshots > 7)
{
syrupshots = 3;
}
System.out.println(syrupshots);
I am not sure why syrupshots is always = 3 no matter what.
Not always, sometimes it returns 1 or 2. But never >3, like it looks like it should.
Your problem is with logical operator precedence. For example:
if(size == 1 && syrupshots < 1 || syrupshots > 3) {}
If size=3 and syrupshots=5 (a valid combination), then this if block is still entered because the && is evaluated first:
size == 1 && syrupshots < 1
and that equals false, so you have left (false || syrupshots > 3)
BUT then the || is evaluated, syrupshots > 3 is true, so the whole expression is true
You need to change the order of precedence by using brackets:
if(size == 1 && (syrupshots < 1 || syrupshots > 3)) {}
As one comment says, all conditions trigger syrupshots to be assigned three. Also, I don't think you wrote your test condiiotns correctly, judging from your comments.
if(size == 1 && syrupshots <= 3)
^That would be proper way to test for the check outlined in your comment

Checking if Element Exists in Boolean Array

I took a programming class, and I'm revisiting old programs that I did not quite get right. This one is a Game Of Life program, and I have a question about code cleanup.
I need to make sure that an array element is in bounds before checking whether its neighbor's boolean value is true or false. I have a statement to check if firstGen[0][0]'s top-left (up one row, left one column) is in bounds. Is there an easier or more elegant way to check if an element is in bounds or to restrict the element checks to the boundaries of a given array without using four && conditionals per if statement?
Note that I have only changed the first if statement thus far, so there may be errors elsewhere. I also excluded the boundary checks for the other neighbors.
public static boolean[][] generation(boolean[][] firstGen)
{
int length = firstGen.length;
boolean[][] newGen = new boolean[length][length];
for (int j = 0; j < firstGen[0].length; j++)
{ for (int i = 1; i < firstGen.length; i++)
{
int count = 0;
if ((i-1 >= 0) && (i-1 < length) && (j-1 >= 0) && (j-1 < length)) //top-left element exists
{ if (newGen[i-1][j-1] == true) count++; } //increment `count` if top-left element is true
if ((newGen[i][j] == false) && (count == 3)) newGen[i][j] = true;
else if ((newGen[i][j] == true) && (count == 1)) newGen[i][j] = false;
else if ((newGen[i][j] == true) && (count > 3)) newGen[i][j] = false;
else break;
}
}
return newGen;
}
If i and j are in bounds, then you know for sure that i - 1 < length and j - 1 < length are both true.
Also:
i - 1 >= 0 can be written i > 0
if (condition == true) can be rewritten if (cond)
So you could replace:
if ((i-1 >= 0) && (i-1 < length) && (j-1 >= 0) && (j-1 < length)) //top-left element exists
{ if (newGen[i-1][j-1] == true) count++; } //increment `count` if top-left element is true
by:
//increment `count` if top-left element is true
if (i > 0 && j > 0 && newGen[i-1][j-1]) count++;
That's the best way I can think of to check if its out of bounds, but an alternative method in general, and one that I think gives programs like the Game of Life more exciting outcomes, is adding periodic boundaries. Basically this means that if you walk off one edge, you end up on the other side (like in pac-man). It sounds complicated, but really all it takes is the % function, which returns the remainder of division between the two numbers given.
So:
27 % 5 = 2;
So for adding periodic boundries you would update x and y positions like this:
x = (x + xStep + horizontalSize) % horizontalSize;
y = (y + yStep + verticalSize) % verticalSize;
Where xStep and yStep are +1 or -1 depending on what direction you want to go. (this works nicely with a for loop) The addition of the size is to make sure you go below zero when you get close to borders.
Then you never have to worry about messy border conditions, everything simply overlaps. No need to check each and every border. I hope this makes sense. Please ask for clarification if not. I've used this more for random walker programs but the idea is the same.

Categories