I do not think my else statement is being executed, why is this?
CodingBat Java String-1 conCat
public String conCat(String a, String b) {
if (a.length() > 0 && b.length() > 0)
if (a.substring(a.length()-1) != b.substring(0,1)) {
return a + b; }
else {
return a + b.substring(1);
}
}
why doesn't this code work?
Re: I do not think my else statement is being executed, why is this?
Because motorcycles don't have doors!
Perhaps you can provide more information about "doesn't work" means.
Re: I do not think my else statement is being executed, why is this?
I assume you mean it doesn't compile. The reason is because if the first condition is not met, you are returning anything.
Here is the same code with braces:
Code:
public String conCat(String a, String b) {
if (a.length() > 0 && b.length() > 0) {
if (a.substring(a.length() - 1) != b.substring(0, 1)) {
return a + b;
}
else {
return a + b.substring(1);
}
}
}
To catch these types of errors, always use the curly braces with your if statements.
Regards,
Jim
Re: I do not think my else statement is being executed, why is this?
CodingBat Java String-1 conCat
could you please have a look at the link and answer based on the requirements of that question?
I tried the brackets to no avail.
thanks.
Re: I do not think my else statement is being executed, why is this?
I understand the requirements. Did your program compile or did the site report an error?
Regards,
Jim
Re: I do not think my else statement is being executed, why is this?
Error: public String conCat(String a, String b) {
^^^^^^^^^^^^^^^^^^^^^^^^^^
This method must return a result of type String
I added a return ""; to fix this problem, but now abccat returns abcat
only dogcat => dogcat works.
Re: I do not think my else statement is being executed, why is this?
*sorry abc cat => abccat
should return abcat
Re: I do not think my else statement is being executed, why is this?
Quote:
Originally Posted by
al_saodiyya
Please go through these pages:
http://www.java-forums.org/forum-gui...w-members.html
BB Code List - Java Programming Forum - Learn Java Programming
Then post your code on the forum -- or at least enough of it to demonstrate the problem.
We don't like forum threads that lose context because the original poster removed the external files that provided that context. A forum is a community resource; let's honor that.
db
Re: I do not think my else statement is being executed, why is this?
I posted the requirements for others on this forum. Please do so in the future.
Quote:
Given two strings, append them together (known as "concatenation") and return the result. However, if the concatenation creates a double-char, then omit one of the chars, so "abc" and "cat" yields "abcat".
conCat("abc", "cat") → "abcat"
conCat("dog", "cat") → "dogcat"
conCat("abc", "") → "abc"
So your statement tells me it is working.
Regards,
Jim