1

I'm starting to learn to use Java.

I'm stuck on a problem in codingbat (http://codingbat.com/prob/p123384): here is my code

public String frontBack(String str) { 
 if (str.length() > 1)
  {
   char first = str.charAt(0);
   char last = str.charAt(str.length()-1);
   String middle = str.substring(1,(str.length()-1));
   return last + first + middle;
  } 
 else 
   return str; 
 } 

And here is the output:

(I can't put an image as I'm a new user)

                         Expected:       Run:       
 frontBack("code") →      "eodc"        "200od"      X      
 frontBack("a") →         "a"           "a"          OK     
 frontBack("ab") →        "ba"          "195"        X      
 frontBack("abc") →       "cba"         "196b"       X      
 frontBack("") →          ""            ""           OK     
 frontBack("Chocolate") → "ehocolatC"   "168hocolat" X    
 frontBack("aavJ") →      "Java"        "171av"      X      
 frontBack("hello") →     "oellh"       "215ell"     X     

Why do I get all these fancy numbers? My solution is fairly similar to the solution provided by codingbat...

Morgan Thrapp
  • 9,748
  • 3
  • 46
  • 67
Gloomy
  • 1,091
  • 1
  • 9
  • 18

1 Answers1

0

Java is assuming that you want to do Integer addition on your chars, then appending your string.

To force string concatenation, you could use a StringBuilder, or something like:

return "" + last + first + middle;

or

return new String(last + first + middle);
Andrew Stubbs
  • 4,322
  • 3
  • 29
  • 48
  • Thanks a lot, indeed it works! however how is it that the sum of two chars gives an integer? O.o – Gloomy Jul 15 '14 at 11:19
  • See here: http://stackoverflow.com/questions/8688668/in-java-is-the-result-of-the-addition-of-two-chars-an-int-or-a-char – Andrew Stubbs Jul 15 '14 at 11:22