Reputation: 1654
Errors with missing return statement. Anyone have any idea what's wrong with the code?
import java.text.*;
public class Sentence {
private String text;
public Sentence(String str) {
str = text;
}
public boolean isPalindrome() {
int length = text.length();
for(int n = 0;n <= length/2;n++) {
char letterFromFront = text.charAt(n);
char letterFromBack = text.charAt(length);
if(letterFromFront == letterFromBack) {
return true;
}else {
return false;
}
}
}
}
Upvotes: 1
Views: 307
Reputation: 34367
Its complaining because there won't be any return if it doesn't enter in the for
loop.
Please add a return
statement after for
loop.
Also please note: n++
in your for
loop is a dead code as your returning in the first iteration itself.
Upvotes: 3
Reputation: 9456
Your code does not take consideration of the case when n is not less than or equal to length/2
.
I suppose that in case if it is not palindrome which means whatever happens ,you want to return false.
public class Sentence {
private String text;
public Sentence(String str) {
str = text;
}
public boolean isPalindrome() {
boolean value = false;
int length = text.length();
for(int n = 0;n <= length/2;n++) {
char letterFromFront = text.charAt(n);
char letterFromBack = text.charAt(length);
if(letterFromFront == letterFromBack) {
value = true;
}else {
value = false;
}
}
return value;
}
}
Upvotes: 1
Reputation: 55798
Actually return false
should be placed after the loop, otherwise it runs always once
public boolean isPalindrome() {
int length = text.length();
for(int n = 0;n <= length/2;n++) {
char letterFromFront = text.charAt(n);
char letterFromBack = text.charAt(length);
if(letterFromFront == letterFromBack) {
return true;
}
}
return false;
}
Upvotes: 1
Reputation: 328568
If length
is -2
for example (which admittedly can't happen), your loop will never run and you will not return anything.
You need to add a return statement after the loop to satisfy the compiler, or even better before your loop, check if length is >1
and return true/false if not.
There are other issues in your code but that is the reason for the compiler error.
Upvotes: 1
Reputation: 864
remove return statment from else clause and move before the end of loop. So if number is palindrome it falls in if clause and returns true and if not it returns false. Theoratically you code is right but the compiler doesnt see it this way.
Upvotes: 0
Reputation: 1499790
anyone have any idea what's wrong with the code?
Exactly what it says.
Put it this way: what do you think this is going to return if the string is empty? (In fact, it will throw an exception because you probably want your upper bound to be exclusive rather than inclusive, but fundamentally you need to consider the case where it never goes into the body of the loop.)
There are other things wrong with this code, mind you:
text.charAt(length)
is going to throw an exception, alwaystrue
when you've finished the loop...)Upvotes: 1