Boolean Value Confusion when it is local, open and recursive in Java - java

I am a beginner and really confused with this code as what happens to boolean value, "done". I have spent two hours understanding this code and I am very frustrated.
public boolean traverse(int row, int column){
boolean done = false;
if(row == grid.length-1 && column == grid[0].length-1)
done = true;
else{
done = traverse(row + 1. column); //down
if(!done) done = traverse (row, column+1)//right
}
if (done) grid[row][column] = PATH;
}
return done;
}
First, "done" is declared FALSE. Then it moves to an if and else statement and becomes local to it.Now, outside the IF and ELSE statement, when it says if(done) do something, it is when done is FALSE or TRUE? Also while in the ELSE statement does (!done) mean that it is FALSE as it is declared TRUE in IF ELSE statement?
In simple words, when you use an IF, IF and ELSE statement with a boolean in it, does it mean it has to be TRUE?
For instance:
boolean love = false;
if(love) do this;
Now, does it mean "do this" when love is false?

The ! operator negotiates the boolean value. That means a statement becomes true if the boolean variable is false. So, for your example this won't be executed:
boolean love = false;
if(love) do this; //not executed
But with a ! it would be executed:
boolean love = false;
if(!love) do this; //executed
In the other case this wouldn't be executed:
boolean love = true;
if(!love) do this; //not executed
EDIT:
For further explanations on if-Statements maybe you will have a look on the official docs by oracle:
http://docs.oracle.com/javase/tutorial/java/nutsandbolts/if.html
EDIT 2:
Maybe if you write your code this way it is more understandable for you:
public boolean traverse(int row, int column){
boolean done = false;
if(row == grid.length-1 && column == grid[0].length-1) {
done = true;
}else{
done = traverse(row + 1. column); //down
if(!done) {
done = traverse (row, column+1)//right
}
}
if (done) {
grid[row][column] = PATH;
}
return done;
}

Related

writing a java method that returns a boolean from a search

I have written a method that searches a tree to test if any integers are negative.
But I am struggling to get the right Boolean value returned. Any pointers as to where I am going wrong?
What I want to achieve is that as soon as the condition statement is met a false is returned but unfortunately my code is always returning a true
static boolean allE(Tree<Integer> x) {
if (x.isEmpty()) return true;
else {
if (x.getValue()%2 != 0) return false;
}
allE(x.getLeft());
allE(x.getRight());
return true;
}
When you recurse on allE you need to consider the result of that recursion. Easiest fix I see, change
allE(x.getLeft());
allE(x.getRight());
return true;
to
return allE(x.getLeft()) && allE(x.getRight());
Although, I think it makes more sense to write the algorithm such that you recurse on even explicitly. And allE saves three letters compared to allEven (please use meaningful names for methods and variables). Something like,
static boolean allEven(Tree<Integer> node) {
if (node.isEmpty()) {
return true;
} else if (node.getValue() % 2 == 0) {
return allEven(node.getLeft()) && allEven(node.getRight());
}
return false;
}
You're not using the results of your recursive tests properly.
It should be:
if (x.isEmpty()) {
return true;
}
boolean thisNodeEven = x.getValue() % 2 == 0;
return thisNodeEven && allE(x.getLeft()) && allE(x.getRight());
I suppose you need to evaluate the return-value of the recursive calls:
static boolean allE(Tree<Integer> x)
{
if (x.isEmpty())
return true;
else {
if (x.getValue()%2 != 0) return false;
}
if(!allE(x.getLeft()) || !allE(x.getRight()))
return false;
return true;
}

Trying to compile code but keep getting the same error?

I keep getting the error: "missing return statement." Isn't my return statement listed 5 times? Does anyone know why I'm getting this and how to fix it? It refers to the second to last bracket. Any help/ideas as to why this is happening is appreciated. Thanks.
public class words
{
// instance variables - replace the example below with your own
private String w;
/**
* Default Constructor for objects of class words
*/
public words()
{
// initialise instance variables
w="";
}
/**
* Assignment constructor
*/
public words(String assignment)
{
w=assignment;
}
/**
* Copy constructor
*/
public words(words two)
{
w=two.w;
}
/**
* Pre: 0<=i<length( )
* returns true if the character at location i is a vowel (‘a’, ‘e’, ‘i', ‘o’, ‘u’ only), false if not
*/
private boolean isVowel(int i)
{
if (w.charAt(i)=='a')
return true;
else if (w.charAt(i)=='e')
return true;
else if (w.charAt(i)=='i')
return true;
else if (w.charAt(i)=='o')
return true;
else if (w.charAt(i)=='u')
return true;
}
}
Tell me what do you return if w.charAt(i) is 'b'.
You need to add a last line:
private boolean isVowel(int i)
{
if (w.charAt(i)=='a')
return true;
else if (w.charAt(i)=='e')
return true;
else if (w.charAt(i)=='i')
return true;
else if (w.charAt(i)=='o')
return true;
else if (w.charAt(i)=='u')
return true;
else return false;
}
private boolean isVowel(int i){
//...
return false;
}
You are missing the case when your i is not a vowel.
Problems
Use brackets. Code without them is annoying to read.
Use the && operator when checking multiple if statements with the same body (all return true)
Use a switch statement if you are comparing the same thing (w.charAt(i)) multiple times but they have different bodies
The actual problem you have here is that if w.charAt(i) is not a vowel then it returns nothing. Include a return statement after all your checks
Use a for loop with an array of vowels
(Note: I have intentionally not included code because it is not helpful to give you the answer. If you don't understand any of the terms used above, comment or google them to understand completely. That will allow you to get the most out of the answer.)
private boolean isVowel(int i)
{
if (w.charAt(i)=='a')
return true;
else if (w.charAt(i)=='e')
return true;
else if (w.charAt(i)=='i')
return true;
else if (w.charAt(i)=='o')
return true;
else if (w.charAt(i)=='u')
return true;
return false;//Default return statement if nothing has matched.
}
--You are missing default return statement. If no match found what your metohd will return ?
--It was the issue, i have updated your code here, if nothing found it will return false.
While other people are explaining the code does not compile because of a missing return statement, I would like to point out you can basically do this as an one liner as shown below.
private boolean isVowel(int i) {
return w.charAt(i) == 'a' || w.charAt(i) == e || w.charAt(i) == 'i' || w.charAt(i) == 'o' || w.charAt(i) == 'u';
}
You are missing the return in your code. Ideally you should not have that many returns.
private boolean isVowel(int i)
{
boolean found=false;
if (w.charAt(i)=='a')
found= true;
else if (w.charAt(i)=='e')
found= true;
else if (w.charAt(i)=='i')
found= true;
else if (w.charAt(i)=='o')
found= true;
else if (w.charAt(i)=='u')
found= true;
return found;
}
You have two options
1. to use a flag like above. you should use brackets, that makes the code easy to read.
2. at the end of your code, just add return false.

Primitive-recursive even/odd - what does it do exactly?

I know that this method checks if the integer is even, but how exactly? I understood on examples like fibonacci or factorial how recursion works but not on this on. I think I don't get it because of the syntax.
// Assume n >= 0
public static boolean even(int n) {
return (n<=1) ? (n==0) : !even(n-1);
}
What my problem is: It's a boolean method, why is there no "true" or "false"?
How exactly does it check if it's even? If I would do it in if-statements without recursion I would check it like this:
if((n%2) == 0)
return true;
it's a JAVA short if else:
condition ? trueCase: elseCase;
it equals to below syntax:
if(condition){
trueCase;
}
else{
elseCase;
}
In your code:
return (n<=1) ? (n==0) : !even(n-1);
equals to:
if(n<=1)){
if(n==0){
return true;
}
else{
return false;
}
}
else{
if(even(n-1)){
return false;
}
else{
return true;
}
}
The statements
if((n%2) == 0)
return true;
else
return false;
is equivalent to
return (n%2) == 0;
any expression that evaluates to a boolean value can be used instead of directly using one of the two boolean values.
As for the function named "even", it basically says an integer is even if the previous integer is not even, unless it is smaller than one, in which case it is even if it is zero. Since it evaluates to a boolean value, so you can return it as the return value.
You should note that your function does not work for negative values.

if-else statements and 2d arrays

I am writing a method that checks to see if certain moves of a checkers game are valid by returning true or false. My code works fine when I want to move diagonally (not jumping). However, when I try to see if my piece can jump across another piece, nothing gets returned (no false, no true, no error message, just blank). I have a setLocation method that takes three parameters of the checkers board column, row, and piece color which places a checkers piece at the said location on the board.
How can I get my code to return true or false if I have pieces on the board set and I want to see if a piece can jump over an opposing color piece? curRow and curCol are just the current row and column that the piece is at. destRow and destCol are the destination that I want my piece to go to.
Here's my code:
if (board[curCol][curRow].equals(Piece.WHITE)){
boolean valid=false;
if ((curRow+1==destRow&&curCol+1==destCol)&&board[destRow][destCol].equals(Piece.NONE)){
valid=true;
}else if ((curRow+1==destRow&&curCol-1==destCol)&&board[destRow][destCol].equals(Piece.NONE)){
valid=true;
//jumps up right over piece
}else if ((curRow+2==destRow&&curCol+2==destCol)&&board[destRow-1][destCol-1].equals(Piece.BLACK)){
valid=true;
//jumps up left over piece
else if ((curRow+2==destRow&&curCol-2==destCol)&&(board[destRow-1][destCol+1].equals(Piece.BLACK))){
valid=true;
}else{
return valid;
}
return valid;
}
First of all, Java can't return "blanks". If your method (which you don't show the declaration of) is a boolean method, it MUST return a boolean.
Why not try something like this:
private static board Peice[][] = new Peice[][]
private enum Peice{
BLACK(-1, false),
BLACK_CROWN(-1, true),
WHITE(1, false),
WHITE_CROWN(1, true)
private int direction;
private boolean crowned;
public Peice(int direction, boolean crowned){
this.direction = direction;
this.crowned = crowned;
}
public boolean isLegal(int curRow, int curCol, int destRow, int destCol){
//not valid if the spot is occupied or if the move isn't the same distance each way
if (board[destRow, destCol] != null) || ((Math.abs(destRow - CurRow) != (Math.abs(destCol - curCol)){
return false;
}
if (abs(destRows - curRows) == 1){
return (destRow - curRow == direction) || crowned;
} else if (abs(destRows-curRows) == 2){
return takeMove(curRow, curCol, destRow, destCol);
// anything but 1 or 2 moves diagonal is never ok.
} else{
return false;
}
}
private boolean takeMove(int curRow, int curCol, int destRow, int destCol)
if (!isOpponent(board[(curRow + destRow)/2, (curCol + destCol)/2])){
return false;
}
return (destRow - curRow) * direction > 0 || crowned;
}
private boolean isOpponent(Peice other){
return other.direction != this.direction
}
}

the return statement is available and the compiler still asks for it

I have the below posted method, and as shown it return Boolean data type. I wrote the return statement but though, the compiler gives me an error saying: this method must return a result of type boolean.
Java code:
public boolean isExistGuess(int guess, ArrayList<Integer> arraylist) {
boolean found = false;
if (arraylist.isEmpty())
return false;
for (int i=0; i < arraylist.size(); i++) {
if (arraylist.get(i) == guess)
return true;
else continue;
}
}
You need a return outside the for loop. The method needs to return something in case all the if statements fail.
public boolean isExistGuess(int guess, ArrayList<Integer> arraylist)
{
boolean found = false;
if (arraylist.isEmpty()) return found;
for (int i = 0; i < arraylist.size(); i++)
{
if (arraylist.get(i) == guess) found = true;
}
return found; // Add return here if all else fails
}
Yes you do have return statements, but the Java compiler insists that there is a return statement for all possibilities of paths of execution the code might follow. There is a possibility that the for loop ends and then there is no return statement.
Add a return false; statement after the end of your for loop.
Additionally, the else continue; is unnecessary, because there is nothing else to skip in the for loop iteration.
I would restructure your method slightly based on how you written it.
public boolean isExistGuess(int guess, ArrayList<Integer> arraylist) {
if (arraylist == null || arraylist.isEmpty())
return false;
boolean found = false;
for (int guessItem : arraylist) {
if (guessItem == guess) {
found = true;
break;
}
}
return found;
}
A function with a return type, must end with a return statement; before closing braces.
So, the solution is:
public boolean isExistGuess(int guess, ArrayList<Integer> arraylist) {
boolean found = false;
if (arraylist.isEmpty())
return false;
for (int i=0; i < arraylist.size(); i++) {
if (arraylist.get(i) == guess)
return true;
else continue;
}
return false;
}
There is a programming style, not particular to Java, that insists that modular code should end with only one single return statement.
There are cases in which it is more perspicuous and expedient to ignore this style rule, especially when return statements at the beginning of a code block filter out error conditions early on.
Your code block is short and sweet, though ... and so the styling rule actually makes your code easier to follow and understand. It also makes it more foolproof since you don't need to worry about the value that other return statements in your code are returning to the caller.
TL;DR: I'd try going with this instead:
public boolean isExistGuess(int guess, ArrayList<Integer> arraylist) {
boolean found = false;
if (!arraylist.isEmpty()) {
for (int i=0; i < arraylist.size(); i++) {
found = ((arraylist.get(i).integerValue() == guess));
if (found) break;
}
}
return found;
}
Edit: I like to do the boxing and unboxing of primitives myself. It fosters the illusion that I'm in control.
The problem is that your conditions are not constants so the compiler can't decide if the method will always return something. As an aside, a shorter equivalent version would be:
public boolean isExistGuess(int guess, ArrayList<Integer> arraylist) {
return arraylist.contains(guess);
}

Categories