Tuesday, February 3, 2015

Tuesday, February 3rd

Went upstairs to the Genius Bar with Tommy today. I tried to advertise it because we haven't had one single customer since the beginning of the genius bar... but still no luck. Oh well. Maybe next time there will be somebody...

Besides that, I worked on String 1. I am approaching the end, but I find that the problems are so annoying. I get the general idea most of the time, but there is always one thing missing... and for that reason I don't complete the problem completely. I only really completed two problems today because all the rest had one run that didn't work or something like that... I need to show Mr. Daly these problems on Thursday. There was even one problem, where it showed that the test runs were all correct - but "other tests" was false. How am I supposed to know what to fix in that situation?! It doesn't tell me anything. Thanks CodingBat.

Anyways, today's problem:

Given a string of any length, return a new string where the last 2 chars, if present, are swapped, so "coding" yields "codign". 

lastTwo("coding") → "codign"
lastTwo("cat") → "cta"
lastTwo("ab") → "ba"



public String lastTwo(String str) {


  if (str.length()<=1)
  {
   return str;
// if the string is shorter than 2 characters, then there can't be 2 characters at the end.
  }


  return (str.substring(0,str.length()-2)) + str.substring(str.length()-1) 
//return the string from the beginning to 2 letters until the end + the last letter of the string

+     str.substring(str.length()-2, str.length()-1);
// add to that string the second to last letter from the original string

// in the end, we will have the string with simply the last two letters inversed.
  
}


I know that it seems like I am not progressing much by simply doing CodingBat every class, but the amount that I am learning each time is incredible. Once I finish level 1 of CodingBat I will probably look to move onto something more of my own, like a project of some sort.


No comments:

Post a Comment