lastTwo challenge

Hi,

I am working on below challenge
http://codingbat.com/prob/p194786

I wrote my code as below
public String lastTwo(String str) {
int len=str.length();
if(len>=2){
  return str.substring(0,len-2)+str.substring(len-1)+str.substring(len-2,len-1);
  }
  
}

Open in new window


I am failing with below message
Compile problems:


Error:      public String lastTwo(String str) {
                    ^^^^^^^^^^^^^^^^^^^
This method must return a result of type String

Possible problem: the if-statement structure may theoretically
allow a run to reach the end of the method without calling return.
Consider adding a last line in the method return some_value;
so a value is always returned.

see Example Code to help with compile problems

How to fix and improve my code. Thanks in advance
LVL 7
gudii9Asked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

CPColinSenior Java ArchitectCommented:
0
ozoCommented:
What does your code do when len>=2 is not true?
0
gudii9Author Commented:
Challenge did not specify for case when length less than 2. Should I assume blank string. Please advise
0
Determine the Perfect Price for Your IT Services

Do you wonder if your IT business is truly profitable or if you should raise your prices? Learn how to calculate your overhead burden with our free interactive tool and use it to determine the right price for your IT services. Download your free eBook now!

ozoCommented:
Challenge tests include
lastTwo("a") → "a"      
lastTwo("") → ""
0
krakatoaCommented:
You didn't read or didn't grasp the question properly, because it explicitly says that you are given a string of any length. "Any" must include zero. Another clue is that the Q says "last two chars, if present . . . "
0
gudii9Author Commented:
public String lastTwo(String str) {
int len=str.length();
if(len>=2){
  return str.substring(0,len-2)+str.substring(len-1)+str.substring(len-2,len-1);
  }
  else{
  return "";
  }
  
}

Open in new window


when i wrote as above failing test case as below for single character.
Expected	Run		
lastTwo("coding") → "codign"	"codign"	OK	    
lastTwo("cat") → "cta"	"cta"	OK	    
lastTwo("ab") → "ba"	"ba"	OK	    
lastTwo("a") → "a"	""	X	    
lastTwo("") → ""	""	OK	    
other tests
OK	   

Open in new window


i do not see any info regarding single character string in the challenge. please advise
0
ozoCommented:
I see info in the challenge test that says
lastTwo("a") → "a"

Reading between the lines of the challenge description, one might suppose that if two characters are not present in the input string, then no swapping is performed on it.
0
gudii9Author Commented:
lastTwo("a") → "a"

I see above only in the test results section. Not in the challenge description.

As you mentioned i took care of that case also by keeping same character
public String lastTwo(String str) {
int len=str.length();
if(len>=2){
  return str.substring(0,len-2)+str.substring(len-1)+str.substring(len-2,len-1);
  }
  if(len==1){
  return str.substring(0);
  }
  else{
  return "";
  }
  
}

Open in new window


i passed all tests. Does my code looks fine?
any improvements to it. Please advise
0
krakatoaCommented:
Not in the challenge description.

But it DOES! It says ANY length, and that must include the possibility of zero length.

All you needed here :
if(len==1){
  return str.substring(0);
  }

Open in new window

is
if(len==1){
return str;
}

Open in new window

0
awking00Information Technology SpecialistCommented:
Another possibility is to use StringBuilder
public String lastTwo(String str) {
StringBuilder sb = new StringBuilder(str);
int len=sb.length();
if(len>=2){
  char lastChar = sb.charAt(len - 1);
  char beforeLastChar = sb.charAt(len - 2);
  sb.setCharAt(len - 1, beforeLastChar);
  sb.setCharAt(len - 2, lastChar);
}
return sb.toString();
}
0
gudii9Author Commented:
public String lastTwo(String str) {
int len=str.length();

StringBuilder sb=new StringBuilder(str);
if(len>=2){
char lastChar=sb.charAt(len-1);
char beforeLastChar=sb.charAt(len-2);
sb.setChar(len-1,beforeLastChar);
sb.setChar(len-2,lastChar);


  }
    return sb.toString();
  
}

Open in new window


when i tried as above getting below error

Compile problems:


Error:      sb.setChar(len-1,beforeLastChar);
         ^^^^^^^
The method setChar(int, char) is undefined for the type StringBuilder


see Example Code to help with compile problems


please advise
0
gudii9Author Commented:
not sure how above is different from below working code
public String lastTwo(String str) {
StringBuilder sb = new StringBuilder(str);
int len=sb.length();
if(len>=2){
  char lastChar = sb.charAt(len - 1);
  char beforeLastChar = sb.charAt(len - 2);
  sb.setCharAt(len - 1, beforeLastChar);
  sb.setCharAt(len - 2, lastChar);
}
return sb.toString();
}

Open in new window

0
ozoCommented:
setChar is different from setCharAt
0
gudii9Author Commented:
Oh when to use each one. How are they different.  Please advise
0
ozoCommented:
setCharAt is a StringBuilder method that you can use when you want to set the character at a specified index http://docs.oracle.com/javase/7/docs/api/java/lang/StringBuilder.html#setCharAt%28int,%20char%29

StringBuilder objects do not have a setChar method, so you can never use it on a StringBuilder object
(although you might use setChar on an Array object, or a Field object or some other object that actually has such a method)
0
gudii9Author Commented:
Oh
0
gudii9Author Commented:
setChar() works similar setCharAt() right for other objects like array etc(non string builder objects).
Please advise
0
ozoCommented:
Yes, they do work similarly for different objects, so you could rewrite your routine to use an Array instead of a StringBuilder, and then use setChar() instead of setCharAt()
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Java

From novice to tech pro — start learning today.