My method can't return boolean - java

I am newbie in java.
Here is my code:
public boolean endsLy(String str) {
if(str.length()>=2){
if(str.substring(str.length()-2).equals("ly")) return true;
}
else return false;
}
but compiler gives:
Error: public boolean endsLy(String str) {
This method must return a result of type boolean
Possible problem: the if-statement structure may theoretically
allow a run to reach the end of the method without calling return.
Consider adding a last line in the method return some_value;
so a value is always returned.

You are not handling the branch where (str.length()>=2, but !str.substring(str.length()-2).equals("ly"). Remove the else from the final return statement:
public boolean endsLy(String str) {
if(str.length()>=2){
if(str.substring(str.length()-2).equals("ly")) return true;
}
return false;
}
An even simpler alternative (also less prone to the kind of error you are having), is to have only a single return statement:
public boolean endsLy(String str) {
return str.length()>=2 && str.substring(str.length()-2).equals("ly");
}

Or simply :
public static boolean endsLy(String str) {
return str.length()>= 2 && str.substring(str.length()-2).equals("ly");
}
You might also check if the String is not null.
return str != null && str.length()>= 2 && str.substring(str.length()-2).equals("ly");

here a correction:
public boolean endsLy(String str) {
if(str.length()>=2){
if(str.substring(str.length()-2).equals("ly"))
return true;
else
return false;
}
else{
return false;
}
}

This error means that there might be a possibility that the function will not return anything under some circumstances.
so if this condition => if(str.length()>=2) stands true the code will enter into it. Now if this condition is false => if(str.substring(str.length()-2) the function will have nothing to return. So this is a wise thing that the error prompted.
This means that not all conditions in this function return a bool value. There is a chance that conditions may occur when function does not have anything to return.

because you do not have a boolean value is returned in case !str.substring (str.length () -2). equals ("ly")
if you want to check that your chain is composed of four characters in the last two are "ly" you can use the following codes:
public boolean endsLy(String str) {
if (str.length() == 4 && str.endsWith("ly"))
return true;
return false;
}

Avoid multiple false return statement as return value is true only for condition if(str.substring(str.length()-2).equals("ly")). Following code is for reference.
public boolean endsLy(String str) {
if(str.length()>=2){
if(str.substring(str.length()-2).equals("ly"))
return true;
}
return false;
}

Related

Java - Passing a char variable to a method and returning a boolean?

Hello I am very new to Java, I wanted to know if it were possible to pass a character to a method, and then return true if this character is valid.
I have this method:
public void btnColor(char c) {
if (hm.getHiddenWordUpdated().contains(String.valueOf(c))) {
// Change button color
}
}
What I would like is to have something like this, although it won't let me do this:
public boolean btnColor(char c, boolean b) {
if (hm.getHiddenWordUpdated().contains(String.valueOf(c))) {
return true;
}
}
So it takes a character variable c and returns true if valid. Is there a best practice for this sort of thing?
You can do something like this in order to always return some value. This should be possible and acceptable with Java.
public boolean btnColor(char c, boolean b) {
if (hm.getHiddenWordUpdated().contains(String.valueOf(c))) {
return true; // this will return in case of your condition is true
}
return false; // this will return otherwise.
}
try this single line
public boolean btnColor(char c, boolean b) {
return hm.getHiddenWordUpdated().contains(String.valueOf(c));
}
It'll return true or false.
When you have public boolean methodName, it means it MUST return a boolean. Having an "IF" statement in your code, means it can split up to a two possible ways: IF-true and IF-false. You have declared the true statement:
if (hm.getHiddenWordUpdated().contains(String.valueOf(c))) {
return true;
So you are covering 1/2 of the solution. But what if it is false ? Nothing ? This is why you have problems, so to solve your problem you code should looks like this:
public boolean btnColor(char c) {
if (hm.getHiddenWordUpdated().contains(String.valueOf(c))) {
return true;
} else {
return false;
}
Now if it is containing the character - it returns TRUE, but if it is not containing it returns FALSE.
All code paths need to return a value.
public boolean btnColor(char c, boolean b) {
if (hm.getHiddenWordUpdated().contains(String.valueOf(c))) {
// add additional code
return true;
}
return false;
}
Alternatively, you could use conditionals in a single line:
public boolean btnColor(char c) {
return (hm.getHiddenWordUpdated().contains(String.valueOf(c))) ? true:false;
}

Missing return statement in Java/Kmax

I am writing a Data Acquisition Software using Sparrow's platform Kmax. This platform has it's own classes and methods, that one has to have worked with it to be familiar. I am trying to make a checkbox button to do a job. To do that, I need to convert a string 1 or 0 to boolean true or false respectively. For this task I built the simple method that follows
public static boolean stringToBool(String s) {
if (s.equals("1"))
return true;
if (s.equals("0"))
return false;
}
When I am trying to compile it I get an error
Runtime.java:30: error: missing return statement }
Note that line 30 is the last line(i.e. } ) of the previous code.
I don't see any point on what could be wrong. Any ideas?
Say those cases aren't true (that s is not equal to "1" or "0"), then what? You must return a default value at the end (which doesn't seem to be a good idea for your code if you are only expecting those two values) or throw an Exception:
public static boolean stringToBool(String s) {
if (s.equals("1")){
return true;
}
if (s.equals("0")){
return false;
}
throw new Exception("0 or 1 Required");
}
There needs to be a return statement executed in all cases, but you don't have a return statement if both if statements are false.
Provide a default case at the end:
return true;
}
The compiler does not know that your String will always be "1" or "0". Therefore, as a safety measure, it ensures that you are required to return some value (although you may never actually return it in practice).
I suggest you return false by default.
public static boolean stringToBool(String s) {
if (s.equals("1")){
return true;}
if (s.equals("0")){
return false;}
return false;
}
You have several options. You code cannot compile because your code must have a return statement always, but, when you put it within the if statemens the compiler cannot find a return for every possible execution path.
public static final String TRUE = "1";
public static final String FALSE = "0"
public static boolean stringToBool(String s) {
boolean result = false;
if (s.equals(TRUE)){
return true;
}
return result;
}
public static boolean stringToBool2(String s) {
boolean result = false;
switch(s) {
case FALSE:
result = false;
break;
case TRUE:
result = true;
break;
default:
// Uuups. Throw exception or return false
}
return result;
}

Java nested for related query

Why isn't this structure acceptable? Anyway it returns a boolean value right??
public boolean a()
{
if(condition)
{
if(condition)
{
if(condition)
{
return true;
}
}
}
}
It's not valid because there is a possibilty where nothing is returned. Your method is declared as returning a boolean value, so it MUST return a boolean value at some point in the code before the method is finished, regardless of the inner logic. If your if-statement if (condition) is false, the method doesn't have another return statement, so the code won't even compile. To fix this, add a "default" return value:
public boolean a()
{
if(condition)
{
if(condition)
{
if(condition)
{
return true;
}
}
}
return false;
}
Not valid because you need to do a return some default value (return) .
What if conditions not satisfied ??
valid is :
public boolean a()
{
if(condition)
{
if(condition)
{
if(condition)
{
return true;
}
}
}
return false;
}
As a side note,To make your code mode readable,I suggest
if(condition && condition && condition)
{
return true;
}
return false;
Prefer to read jls-14.17
Though the method returns true when the condition is satisfied, it doesn't specify a return value when the condition isn't satisfied. The method should cover all the code paths (read conditional statements).
As the answers above correctly state, you absolutely have to return something in Java. C doesn't really care.
In order to avoid this I would recommend decreasing the level of nesting to do something like
boolean value=false; //default return
if(cond && cond)
return value;
if(cond)
return false; //if you want to be more specific
if(cond)
value=true;
return value;
so a value gets returned no matter what. On the plus side, readability increases

Bool vals won't print out in console

I am interested in a very simple string verification problem to see if the starting character in a string starts with an upper case letter and then have the console to display true or false. From my understanding you wouldn't have to invoke something like System.console().printf("true", s) in order to make this happen. I could swear I've seen similar elementary implementations achieved using the following sample code:
public class Verify {
public static boolean checkStartChar(String s) {
if (s.startsWith("[A-Z]")) {
return true;
} else {
return false;
}
}
public static void main(String[] args) {
String str = "abCD";
checkStartChar(str);
}
}
but when I run this, nothing displays. If I make a slight modification by adding in conditional printouts before returning T/F, e.g.
public class Verify2 {
public static boolean checkStartChar(String s) {
if (s.startsWith("[A-Z]")) {
System.out.println("yep");
return true;
}
else {
System.out.println("nope");
return false;
}
}
public static void main(String[] args) {
String str = "abCD";
checkStartChar(str);
}
}
the issue is somewhat resolved, as the console displays either "yep" or "nope", yet unresolved because I just want the console to display true or false. That's it. Advice?
As the question has already been answered, I'd like to point out there is no need for RegExes to solve this (and they are expensive operations). You could do it simply like this:
static boolean startsWithUpperCase(String toCheck)
{
if(toCheck != null && !toCheck.isEmpty())
{
return Character.isUpperCase(toCheck.charAt(0));
}
return false;
}
yet unresolved because I just want the console to display true or false
Calling checkStartChar method will return value, that doesn't mean it will print value to console. You need to code how you would like to handle return value. If you want to print return value, then you should do:
System.out.println(checkStartChar(str));
Will print what ever the return of checkStartChar method
if(s.startsWith("[A-Z]")){
String.startsWith(prefix) doesn't take regex as a parameter, you should be using regex APi instead.
Pattern p = Pattern.compile("[A-Z]");
Matcher m = p.matcher(new Character(s.charAt(0)).toString());
if(m.find()){
return true;
}else{
return false;
}
String str = "AbCD";
System.out.println(checkStartChar(str));
Output:
true
In your code checkStartChar(str); is returning a boolean value which is not being used in your program.Then if you want to display true or false then you can use.
System.out.println(checkStartChar(str));

Comparing boolean values

I am facing an issue while comparing boolean values, I want the loop to enter inside the block but its not entering the block.
else if (!(keyCompare.contains(compareKey)) || (save == true)) {
//do something
}
here !(keyCompare.contains(compareKey) will return false. I am seeing if the vector keyCompare does not have compareKey or if save is true then enter if loop, but its not.
Where I am doing wrong?
There are three possibilities:
An if or else if block above this one is executing.
An exception is being thrown by contains.
You're incorrect and both of those conditions are false.
A debugger will tell you exactly which possibility is correct. There's not really any need for discussion here - those are literally the only three possibilities.
Suppose you have a class as follows:
static class Contents {
private String contents;
public Contents(String contents) {
this.contents = contents;
}
}
Writing the following code:
Vector<Contents> v = new Vector<>();
v.add(new Contents("a"));
System.out.println("Contains a: "+v.contains(new Contents("a")));
Would yield the following output:
Contains a: false
However adding the equals method to the Contents class as follows:
public boolean equals(Object obj) {
return Objects.equals(this.contents, ((Contents)obj).contents);
}
Yields suddenly the following result:
Contains a: true
A better implementation might have looked as follows:
#Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null) return false;
if (getClass() != obj.getClass())return false;
final Contents other = (Contents) obj;
if (!Objects.equals(this.contents, other.contents))return false;
return true;
}

Categories

Resources