Reputation: 21
Here's the link to what I'm doing, simple practice:
http://codingbat.com/prob/p162477
However, its telling me that when it makes front = false,
public String theEnd(String str, boolean front) {
String stringPart;
if (front = true) {
stringPart = str.substring(0, 1);
} else {
stringPart = str.substring(str.length()-1,str.length());
}
return stringPart;
}
returns it as it would when true anyway. I don't wanna learn bad habits :(
EX: Elephant returns E, when it should return t. I'll check back later, i need a LOONNNNG rest. Probably making stupid mistakes
Upvotes: 0
Views: 253
Reputation: 54325
You wrote (front = true) in your if statement. This does not compare front to true. This sets front equal to true.
I am shocked that your compiler did not yell at you for this statement. You should have gotten a warning. If you can, please make sure that you compile with all warning options turned on, then pay attention to each warning.
Upvotes: 0
Reputation: 1500903
This is the problem:
if (front = true)
You meant:
if (front == true)
Currently it's assigning front
a new value of true
, then evaluating that result and finding it's true - so it will always take the first character.
There are three ways of fixing this. One is as above, and just be more careful. One is to use:
if (true == front)
which will prevent you from making the typo, because you can't assign to the constant true
.
However, I'd prefer to get rid of the literal entirely:
if (front)
However, you can also make this whole method simpler with the conditional operator:
public String theEnd(String str, boolean front) {
int start = front ? 0 : str.length() - 1;
return str.substring(start, start + 1);
}
Upvotes: 6