Binary search tree String search - java

I have a program where I need to search for a specific word in a binary tree, the code I came up with for the search method for the string is not working. if someone could take a look at it I would greatly appreciate it.
I have tried a few alterations to this but it still did not work.
public boolean check(BSTNode t,String key){
if(!t.word.equals(key)){
check(t.left,key);
check(t.right,key);
}
else{
return true;
}
return false;
}

This could be written like this;
public boolean check(BSTNode t,String key) {
return
t.word.equals(key) || check(t.left,key) || check(t.right,key)
}
or, more verbosely;
public boolean check(BSTNode t,String key) {
if (t.word.equals(key)) return true;
if (check(t.left,key)) return true;
if (check(t.right,key)) return true;
return false;
}
You don't need a lot of else statements because the return statements stop execution in the function.
Edit:
You must also check to see that your BSTNode is not null, or you will get null pointer exceptions when you reach the end of the tree. This could be done at the start of the function, or before the inner recursive check calls:
public boolean check(BSTNode t,String key) {
if (t == null) return false;
if (t.word.equals(key)) return true;
if (check(t.left,key)) return true;
if (check(t.right,key)) return true;
return false;
}
or;
public boolean check(BSTNode t,String key) {
if (t.word.equals(key)) return true;
if (t.left != null && check(t.left,key)) return true;
if (t.right != null && check(t.right,key)) return true;
return false;
}

Related

Iterator hasNext() Method

Why do we implement hasNext method as
public boolean hasNext() {
if(current != null)
return true;
return false;
}
instead of
public boolean hasNext() {
if(current.getNext() != null)
return true;
return false;
}
I don't know who we is but consider the following.
public boolean hasNext() {
if(current != null)
return true;
return false;
}
In the previous case, next() would return the value and update current.
public boolean hasNext() {
if(current.getNext() != null)
return true;
return false;
}
In this case, if getNext() is null, you still need to return the current value (e.g. current.getValue()) so you would miss the last one.
But keep in mind that hasNext() and next() don't work in isolation of each other. So it depends on how both are implemented as to whether either method makes sense.

Java Beginner Recursion with boolean

I don't understand why I am getting "return statement missing".
Here is the image with the code:
In your 2nd and 3rd if conditions there are no returns. Instead of your else, just return false.
So it reads:
public class isTrans {
public static boolean isTrans(String s,String t) {
if (t.length()==1 && (s.charAt(s.length()-1))==t.charAt(0)){
return true;
} else if (s.charAt(0)==t.charAt(0)){
return isTrans(s,t.substring(1));
} else if (s.charAt(1)==t.charAt(1)){
return isTrans(s,t.substring(1), t);
}
return false;
}
}
In this case you have to return in all the conditions or return at the end of the method.
if(/*...*/) {
return true;
}
else if(/*...*/) {
return isTrans(/*...*/); // return whatever isTrans returns
}
else if(/*...*/) {
return isTrans(/*...*/); // here too
}
else {
return false;
}
You have to return the result of the function execution in your else if, so the recursion works properly. Like this:
return isTrans(s, t.substring(1))

Class equals method is confusing

I'm studying object oriented programming in Java at my school and I had to do an exercise to compare Circles.
I had the Circle Class with these
private int id;
private String bgColor;
private String fgColor;
And inside it I had to use the equals method to compare two circles (by using these three attributes): a circle is equal to other circle if its radius and the bg and fgColor are the same.
public boolean equals(Object obj) {
boolean found;
if (obj == null) {
found = false;
}
if (getClass() != obj.getClass()) {
found = false;
}
final Circle other = (Circle) obj;
if (Double.doubleToLongBits(this.radius) == Double.doubleToLongBits(other.radius)) {
//found = false;
if (Objects.equals(this.bgColor, other.bgColor)) {
//found = false;
if (Objects.equals(this.fgColor, other.fgColor)) {
return true;
}//end if fgColor
else{
found = false;
}
}//end if bgcolor
else{
found = false;
}
}//end if radius
else{
found = false;
}
return found;
}
But my teacher told me that the code above is "confusing", but I don't understand why.
Do you know a better solution?
My teacher wants that we folow this structure (this case is only comparing one property):
public boolean equals (Object obj)
{
boolean b;
if(obj == null)
{
b = false;
}
else
{
if(this == obj)//same object
{
b = true;
}
else
{
if(obj instanceof Book)
{
Book other = (Book) obj;
b = (this.id == other.id);
}
else
{
b = false;
}
}
}
return b;
}
This is about the most concise version (assuming that radius and colors can't be null). The null check for obj is taken care of by the instanceof test:
public boolean equals(Object obj) {
if( ! (obj instanceof Circle ) )
return false;
Circle rhs = (Circle)obj;
return Double.compare( radius, rhs.radius ) == 0 &&
bgColor.equals( rhs.bgColor ) &&
fgColor.equals( rhs.fgColor );
}
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
// its a Circle so its safe to case
Circle other = (Circle)obj;
// equals ONLY if 3 conditions are met
if (radius == other.getRadius() &&
bgColor.equals(other.getBgColor()) &&
fgColor.equals(other.getFgColor())){
return true;
}
return false;
}
If you are using a IDE (I hope you do) probably it has an option to generate code for equals method.
Eclipse generates something like:
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Circle other = (Circle) obj;
if (bgColor == null) {
if (other.bgColor != null)
return false;
} else if (!bgColor.equals(other.bgColor))
return false;
if (fgColor == null) {
if (other.fgColor != null)
return false;
} else if (!fgColor.equals(other.fgColor))
return false;
if (Double.doubleToLongBits(radius) != Double.doubleToLongBits(other.radius))
return false;
return true;
}
And don't forget implements hashcode method when you implements equals method and vicecersa.
Rather than having a single return statement consider using multiple return points to simplify the code. This way you do not need extra boolean variables to hold on to the results of prior conditions.
public class Circle {
public double radius;
public String bgColor;
public String fgColor;
public boolean equals(Object obj) {
if (obj == null) {
return false;
} else if (obj instanceof Circle) {
Circle other = (Circle) obj;
if (Double.compare(this.radius, other.redius) == 0
&& compareStrings(this.fgColor, other.fgColor)
&& compareStrings(this.bgColor, other.bgColor)) {
return true;
} else {
return false;
}
} else {
return false;
}
}
private boolean compareStrings(String a, String b) {
if (a == null && b == null) {
return true;
} else if (a != null) {
return a.equals(b);
} else if (b != null) {
return b.equals(a);
}
return false;
}
}
This solution allows for the possibility that either of the String fgColor or bgColor might be null without throwing a NPE. The String comparison has been extracted into its own function to aid readability and reduce confusion.
As a follow-up to my previous answer:
Writing an equals method that works correctly in the presence of subclassing is extremely non-trivial (see Joshua Bloch's comments in Item 8 of `Effective Java').
Indeed, until relatively recently the was no widely known single method for doing this.
In 2009, the article "How to Write an Equality Method in Java"
by Martin Odersky, Lex Spoon, and Bill Venners shows that this can be achieved in terms of a `canEqual' method.

Missing return statment

I wrote this small program as practice in Java(it simulates the 7 electrical logic gates), as I am currently learning it. But when I try to compile it, it gives me several errors stating "MISSING RETURN STATEMENT", but only for the subroutines that have 2 if statements(AND, OR, NAND and NOR). I am wondering if there is something that I don't know about Java if statements. I am also wondering if there is a way in Java to do if(X && Y), like in C. Anyway, here is the code:
package logic;
public class logic {
boolean AND(boolean A, boolean B) {
if(A==true) {
if(B==true)
return true;
}
else
return false;
}
boolean OR(boolean A, boolean B) {
if(A==false) {
if(B==false)
return false;
}
else
return true;
}
boolean NOT(boolean A) {
if(A==true)
return false;
else
return true;
}
boolean NAND(boolean A, boolean B) {
if(A==true) {
if(B==true)
return false;
}
else
return true;
}
boolean NOR(boolean A, boolean B) {
if(A==false) {
if(B==false)
return true;
}
else
return false;
}
boolean XOR(boolean A, boolean B) {
if(A==B)
return false;
else
return true;
}
boolean XNOR(boolean A, boolean B) {
if(A==B)
return true;
else
return false;
}
}
and the error message:
logic/logic.java:10: error: missing return statement
}
^
logic/logic.java:18: error: missing return statement
}
^
logic/logic.java:32: error: missing return statement
}
^
logic/logic.java:40: error: missing return statement
}
^
4 errors
all help or suggestions is accepted.
For some reason when I tried to use if(A==true && B==true)before it didn't work, but now it is.
Java is not like Python where the compiler understand that code blocks are stated by simple indentation. I would recommend always using braces { } to open a close a new code block even if is one liner. Just to rewrite one of your gates:
boolean AND(boolean A, boolean B) {
if(A==true) {
if(B==true) {
return true;
}
//missing return here!
//fix it by adding a return
return false;
} else {
return false;
}
}
As others have pointed out, you really miss out some return statements. Here is the short version you are looking for:
public class Logic {
boolean AND(boolean A, boolean B) {
return A && B;
}
boolean OR(boolean A, boolean B) {
return A || B;
}
boolean NOT(boolean A) {
return !A;
}
boolean NAND(boolean A, boolean B) {
return !(A && B);
}
boolean NOR(boolean A, boolean B) {
return !(A || B);
}
boolean XOR(boolean A, boolean B) {
return A ^ B;
}
boolean XNOR(boolean A, boolean B) {
return !(A ^ B);
}
}
Note that class names in Java should start with a capital letter by convention.
You lack return statements for some code paths.
In OR, what happens if A is true and B is false?
Some of your methods have paths that result in no return value.
For example:
boolean NOR(boolean A, boolean B) {
if(A==false) {
if(B==false)
return true;
}
else
return false;
}
If A == false and B == true, there is no return statement to run. This is why you are getting that compiler error.
This is perhaps made more obvious by putting brackets around all of your if statements:
boolean NOR(boolean A, boolean B) {
if(A==false)
{
if(B==false)
{
return true;
}
//No return here
}
else
{
return false;
}
//No return here
}
Aside from the return statement errors, you are making your code way too complex. Java already has compound logical operators that can greatly simplify how you are reasoning about your program.
// no need for A == true, A is either already true or false
// just combine them using the && operator
boolean AND(boolean A, boolean B) {
return A && B;
}
Similarly for OR:
boolean OR(boolean A, boolean B) {
return A || B;
}
You can also build logic gates from other logic gates, EX NOT + OR == NOR
boolean NOT(boolean A) {
return !A;
}
boolean OR(boolean A, boolean B) {
return A || B;
}
Combine the two to create NOR:
boolean NOR(boolean A, boolean B) {
return NOT( OR(A, B) );
}
Using this, see if you can compose the rest yourself.
Missing return statement error means that The function declaration says it returns something, but there exists atleast one flow where it does not return anything. Eg. In the code for And - if A is true and B is false. Modified the code :
package logic;
public class Logic {
boolean AND(boolean A, boolean B) {
if (A == true && B == true) {
return true;
}
return false;
}
boolean OR(boolean A, boolean B) {
if (A == false && B == false) {
return false;
}
return true;
}
boolean NOT(boolean A) {
if (A == true) {
return false;
}
return true;
}
boolean NAND(boolean A, boolean B) {
if (A == true && B == true) {
return false;
}
return true;
}
boolean NOR(boolean A, boolean B) {
if (A == false && B == false) {
return true;
}
return false;
}
boolean XOR(boolean A, boolean B) {
if (A == B) {
return false;
}
return true;
}
boolean XNOR(boolean A, boolean B) {
if (A == B) {
return true;
}
return false;
}
}
There are possible values that could result in no value being returned, remember an if has an empty else{} whether you give it one or not, so lets look at one of your functions
boolean AND(boolean A, boolean B) {
if(A==true) {
if(B==true)
return true;
}else{
//else made explicit by me
//NO RETURN
}
}
else{
return false;
}
}
So if A was true but B was false nothing would be returned, the compiler cannot allow this
Its also unwise to use the multiline-braceless-if because it makes it easier to make these sorts of error. See http://cafe.elharo.com/blogroll/braceless-if-considered-harmful/
you must have a return statement for all possible "paths". For example
boolean AND(boolean A, boolean B) {
if(A==true) {
if(B==true)
return true;
}
else
return false;
}
is equivalent to
boolean AND(boolean A, boolean B) {
if(A==true) {
if(B==true)
return true;
else
//something must be returned here
}
else
return false;
}
You can also have a return null; statement at the end of every method to avoid this error.

How to return a boolean method in java?

I need help on how to return a boolean method in java. This is the sample code:
public boolean verifyPwd(){
if (!(pword.equals(pwdRetypePwd.getText()))){
txtaError.setEditable(true);
txtaError.setText("*Password didn't match!");
txtaError.setForeground(Color.red);
txtaError.setEditable(false);
}
else {
addNewUser();
}
return //what?
}
I want the verifyPwd() to return a value on either true or false whenever I want to call that method. I want to call that method like this:
if (verifyPwd()==true){
//do task
}
else {
//do task
}
How to set the value for that method?
You're allowed to have more than one return statement, so it's legal to write
if (some_condition) {
return true;
}
return false;
It's also unnecessary to compare boolean values to true or false, so you can write
if (verifyPwd()) {
// do_task
}
Edit: Sometimes you can't return early because there's more work to be done. In that case you can declare a boolean variable and set it appropriately inside the conditional blocks.
boolean success = true;
if (some_condition) {
// Handle the condition.
success = false;
} else if (some_other_condition) {
// Handle the other condition.
success = false;
}
if (another_condition) {
// Handle the third condition.
}
// Do some more critical things.
return success;
try this:
public boolean verifyPwd(){
if (!(pword.equals(pwdRetypePwd.getText()))){
txtaError.setEditable(true);
txtaError.setText("*Password didn't match!");
txtaError.setForeground(Color.red);
txtaError.setEditable(false);
return false;
}
else {
return true;
}
}
if (verifyPwd()==true){
addNewUser();
}
else {
// passwords do not match
System.out.println("password do not match");
}
public boolean verifyPwd(){
if (!(pword.equals(pwdRetypePwd.getText()))){
txtaError.setEditable(true);
txtaError.setText("*Password didn't match!");
txtaError.setForeground(Color.red);
txtaError.setEditable(false);
return false;
}
else {
addNewUser();
return true;
}
}
You can also do this, for readability's sake
boolean passwordVerified=(pword.equals(pwdRetypePwd.getText());
if(!passwordVerified ){
txtaError.setEditable(true);
txtaError.setText("*Password didn't match!");
txtaError.setForeground(Color.red);
txtaError.setEditable(false);
}else{
addNewUser();
}
return passwordVerified;
Best way would be to declare Boolean variable within the code block and return it at end of code, like this:
public boolean Test(){
boolean booleanFlag= true;
if (A>B)
{booleanFlag= true;}
else
{booleanFlag = false;}
return booleanFlag;
}
I find this the best way.

Categories