Reputation: 861
I am going through a list of questions on a past examination paper. One of the questions is of type boolean.
It should return false if the name is not Thomas, and true if it is.
Here is my code:
public class QuestionTwo
{
String name;
public static void main(String [] args){
System.out.println(nameTest("Thomas"));
}
public static boolean nameTest(String name){
if(!name.equals("Thomas"));
return false;
}
}
As you can see my code should return true, but it keeps returning false? Can someone tell me where I seem to have gone wrong with my code please? Please forgive any silly errors found as I am still learning. Many thanks.
Upvotes: 3
Views: 2687
Reputation: 2402
The best thing to do is to return exactly whether the name equals Thomas. There is no need to do an if statement
public static boolean nameTest(String name){
return name.equals("Thomas");
}
The other proposed solution:
if(!name.equals("Thomas")) return false;
won't compile, because there is no return value in case the name isn't Thomas.
Upvotes: 1
Reputation: 727047
[the method] should return false if the name is not Thomas, and true if it is.
You do not need an if
at all:
public static boolean nameTest(String name){
return name.equals("Thomas");
}
In general, boolean
expressions are easier to read without if
s and == true
/ == false
around them. Every time you see returning true
or false
from a branch of an if
, you should consider rewriting it without the if
statement.
Upvotes: 3
Reputation: 6089
Putting semicolon after if and return statements makes them separate statements. Code should be like :
public class QuestionTwo {
String name;
public static void main(String [] args){
System.out.println(nameTest("Thomas"));
}
public static boolean nameTest(String name){
if(!"Thomas".eqauals(name)) {
return false;
}
return true;
}
}
Upvotes: 1
Reputation: 46438
remove the semicolon at the end of if statement
.
if(!name.equals("Thomas"))
Also good practice is to do equals test
this way:
if(!"Thomas".equals(name))
In this case, if name is null you wouldn't get NPE.
Upvotes: 6
Reputation: 5377
Remove the semicolon
if(!name.equals("Thomas")) return false;
The way you have written it, it is two separate statements. First, if name not equals Thomas then do nothing. Then second, return false.
Upvotes: 6