Solved

last chars java challenge

Posted on 2014-12-04
92
135 Views
Last Modified: 2015-01-30
Hi,

I am working on below challenge

http://codingbat.com/prob/p138183
I wrote my code as below

http://codingbat.com/prob/p138183
I am failing below tests.
Expected	Run		
lastChars("last", "chars") → "ls"	"ls"	OK	    
lastChars("yo", "java") → "ya"	"ya"	OK	    
lastChars("hi", "") → "h@"	"Exception:java.lang.StringIndexOutOfBoundsException: String index out of range: -1 (line number:4)"	X	    
lastChars("", "hello") → "@o"	"Exception:java.lang.StringIndexOutOfBoundsException: String index out of range: 1 (line number:4)"	X	    
lastChars("", "") → "@@"	"Exception:java.lang.StringIndexOutOfBoundsException: String index out of range: 1 (line number:4)"	X	    
lastChars("kitten", "hi") → "ki"	"ki"	OK	    
lastChars("k", "zip") → "kp"	"kp"	OK	    
lastChars("kitten", "") → "k@"	"Exception:java.lang.StringIndexOutOfBoundsException: String index out of range: -1 (line number:4)"	X	    
lastChars("kitten", "zip") → "kp"	"kp"	OK	    
other tests
X	
How to fix and improve my code. Thanks in advance

Open in new window

0
Comment
Question by:gudii9
  • 46
  • 25
  • 11
  • +2
92 Comments
 
LVL 4

Expert Comment

by:Zsolt Pribusz
Comment Utility
You didn't included your code.
0
 
LVL 4

Expert Comment

by:Zsolt Pribusz
Comment Utility
Since you not included your code, I wrote one:
public String lastChars(String a, String b) {
  if(a.length()>0){
  a=a.substring(0,1);
  }
  else
  {
  a="@";
  }
  if(b.length()>0){
  b=b.substring(b.length()-1);
  }
  else
  {
  b="@";
  }
  return a+b;
}

Open in new window

0
 
LVL 4

Assisted Solution

by:Zsolt Pribusz
Zsolt Pribusz earned 167 total points
Comment Utility
Or do it in one line:

public String lastChars(String a, String b) {
return (a+"@").substring(0,1) + ("@"+b).substring(b.length());
}

Open in new window

0
 
LVL 7

Author Comment

by:gudii9
Comment Utility
I missed pasting my code. Some copy paste issue.

Here is the code I tried
public String lastChars(String a, String b) {
int len=a.length();
int leng=b.length();
  return a.substring(0,1)+b.substring(leng-1);
}

Open in new window


Let me re read above posts again
0
 
LVL 84

Expert Comment

by:ozo
Comment Utility
Your code is not handling the possibility of either string being length 0.

Do you understand either of the methods Zsolt Pribusz presented?
0
 
LVL 7

Author Comment

by:gudii9
Comment Utility
public String lastChars(String a, String b) {
int lenA=a.length();
int lenB=b.length();
if(lenA>=0&&lenB>=0)
  return a.substring(0,1)+b.substring(lenB-1);
  if(lenA==0)
   return "@"+b.substring(lenB-1);
   if(lenB==0)
     return a.substring(0,1)+"@";
     
     else
     return"";
   
}

Open in new window


i tried as above but still failing in test cases. please advise howto correct above code.
0
 
LVL 84

Expert Comment

by:ozo
Comment Utility
lenA>=0 is always true
lenB>=0 is always true
0
 
LVL 7

Author Comment

by:gudii9
Comment Utility
public String lastChars(String a, String b) {
int lenA=a.length();
int lenB=b.length();
if(lenA>0&&lenB>0)
  return a.substring(0,1)+b.substring(lenB-1);
  if(lenA==0)
   return "@"+b.substring(lenB-1);
   if(lenB==0)
     return a.substring(0,1)+"@";
   if(lenA==0&&lenB==0)
      return "@"+"@";
     
     else
     return"";
   
}

i corrected and updated my code. falining on one test case. please advise
Expected	Run		
lastChars("last", "chars") → "ls"	"ls"	OK	    
lastChars("yo", "java") → "ya"	"ya"	OK	    
lastChars("hi", "") → "h@"	"h@"	OK	    
lastChars("", "hello") → "@o"	"@o"	OK	    
lastChars("", "") → "@@"	"Exception:java.lang.StringIndexOutOfBoundsException: String index out of range: -1 (line number:7)"	X	    
lastChars("kitten", "hi") → "ki"	"ki"	OK	    
lastChars("k", "zip") → "kp"	"kp"	OK	    
lastChars("kitten", "") → "k@"	"k@"	OK	    
lastChars("kitten", "zip") → "kp"	"kp"	OK	    
other tests

Open in new window

0
 
LVL 84

Expert Comment

by:ozo
Comment Utility
Better, but when both strings are length 0, you never get to any of the tests after if(lenA==0)
0
 
LVL 31

Assisted Solution

by:awking00
awking00 earned 166 total points
Comment Utility
if (a.length() == 0) {
      ltr1 = "@";
} else {
      ltr1 = a.substring(0,1);
}
if (b.length() == 0) {
      ltr2 = "@";
} else {
      ltr2 = b.substring(b.length() - 1);
}
return ltr1 + ltr2;
0
 
LVL 7

Author Comment

by:gudii9
Comment Utility
but when both strings are length 0, you never get to any of the tests after if(lenA==0)

i wonder why. I am checking as below right

if(lenA>0&&lenB>0)//first if loop
  return a.substring(0,1)+b.substring(lenB-1);
  if(lenA==0)//second if loop
   return "@"+b.substring(lenB-1);
   if(lenB==0)//third if loop
     return a.substring(0,1)+"@";
   if(lenA==0&&lenB==0) //fourth if loop
      return "@"+"@";

I thought it will logically flow from first if loop to second to third to fourth. please advise
0
 
LVL 84

Expert Comment

by:ozo
Comment Utility
Once the flow hits a return statement, the current method is exited, and flow returns to the caller.

When both strings are length 0, lenA==0 is true, so the return "@"+b.substring(lenB-1); is executed.
0
 
LVL 7

Author Comment

by:gudii9
Comment Utility
oh i see the point.
0
 
LVL 7

Author Comment

by:gudii9
Comment Utility
wehn i wrote as below still one test case failing
public String lastChars(String a, String b) {
int lenA=a.length();
int lenB=b.length();
String str="";
if(lenA>0&&lenB>0)
  str= a.substring(0,1)+b.substring(lenB-1);
  if(lenA==0)
   str= "@"+b.substring(lenB-1);
   if(lenB==0)
     str= a.substring(0,1)+"@";
      if(lenA==0&&lenB==0) 
      str= "@"+"@";
      
    return str;
   
}

Open in new window


please advise
Expected	Run		
lastChars("last", "chars") → "ls"	"ls"	OK	    
lastChars("yo", "java") → "ya"	"ya"	OK	    
lastChars("hi", "") → "h@"	"h@"	OK	    
lastChars("", "hello") → "@o"	"@o"	OK	    
lastChars("", "") → "@@"	"Exception:java.lang.StringIndexOutOfBoundsException: String index out of range: -1 (line number:8)"	X	    
lastChars("kitten", "hi") → "ki"	"ki"	OK	    
lastChars("k", "zip") → "kp"	"kp"	OK	    
lastChars("kitten", "") → "k@"	"k@"	OK	    
lastChars("kitten", "zip") → "kp"	"kp"	OK	    
other tests
OK	    
Correct for more than half the tests

Open in new window

0
 
LVL 84

Expert Comment

by:ozo
Comment Utility
Now when both strings are length 0, you try to execute both
  str= "@"+b.substring(lenB-1);
and
  str= a.substring(0,1)+"@";
But b.substring(lenB-1) is not valid when lenB==0
(and a.substring(0,1) is not valid when lenA==0)

An easier way to correct your code in http:#a40482866 might be to change the order of the tests it does.
0
 
LVL 7

Author Comment

by:gudii9
Comment Utility
Now when both strings are length 0, you try to execute both
  str= "@"+b.substring(lenB-1);

As per my code i am thinking i am doing  "@"+"@" when both string lenghts are zero

   if(lenA==0&&lenB==0)
      str= "@"+"@";
     
please advise
0
 
LVL 84

Expert Comment

by:ozo
Comment Utility
Before your code gets a chance to do
   if(lenA==0&&lenB==0)
      str= "@"+"@";
it does
  if(lenA==0)
   str= "@"+b.substring(lenB-1);
Which causes it to die with an exception when b.substring(lenB-1) fails because there is no such index as substring(-1)
0
 
LVL 7

Author Comment

by:gudii9
Comment Utility
LenB is not zero right in this if loop. I thought code flow enters if loop when only lenA is zero
0
 
LVL 84

Expert Comment

by:ozo
Comment Utility
The test that is failing is lastChars("", ""), when lenA is zero and LenB is zero.
Code flow enters the conditional statement of
  if(lenA==0)
   str= "@"+b.substring(lenB-1);
when lenA is zero
0
 
LVL 7

Author Comment

by:gudii9
Comment Utility
Ok I see. So I have to change order of if statements to fix
0
 
LVL 7

Author Comment

by:gudii9
Comment Utility
public String lastChars(String a, String b) {
int lenA=a.length();
int lenB=b.length();
String str="";

  if(lenA==0)
   str= "@"+b.substring(lenB-1);
   if(lenB==0)
     str= a.substring(0,1)+"@";
      if(lenA==0&&lenB==0) 
      str= "@"+"@";
      
      if(lenA>0&&lenB>0)
  str= a.substring(0,1)+b.substring(lenB-1);
  
    return str;
   
}

Open in new window

changing order as above. Still one test case failing
Expected	Run		
lastChars("last", "chars") → "ls"	"ls"	OK	    
lastChars("yo", "java") → "ya"	"ya"	OK	    
lastChars("hi", "") → "h@"	"h@"	OK	    
lastChars("", "hello") → "@o"	"@o"	OK	    
lastChars("", "") → "@@"	"Exception:java.lang.StringIndexOutOfBoundsException: String index out of range: -1 (line number:8)"	X	    
lastChars("kitten", "hi") → "ki"	"ki"	OK	    
lastChars("k", "zip") → "kp"	"kp"	OK	    
lastChars("kitten", "") → "k@"	"k@"	OK	    
lastChars("kitten", "zip") → "kp"	"kp"	OK	    
other tests
OK	 

Open in new window


please advise
0
 
LVL 31

Expert Comment

by:awking00
Comment Utility
Your first if statement says if lenA== 0 then str = "@" + b.substring(lenB - 1) so, if lenA and lenB are both 0 then lenA==0 and its assigning the value of "@" + the substring of "" starting at -1, which is always out of bounds. With this approach, you need to test for both lenA and lenB being equal to zero first. For ease of understanding, I still prefer determining the values of strA and strB (either @ or substring) making str = strA + strB.
0
 
LVL 7

Author Comment

by:gudii9
Comment Utility
mistake i am doing is if lenA==0 then building B string using substring vice versa.

Instead i should check lenA>0 then build A string using its substring method else return @

public String lastChars(String a, String b) {
int lenA=a.length();
int lenB=b.length();

String strA="";
String strB="";
String str="";
  if(lenA>0){
   strA= a.substring(0,1);
   }
   else{
   strA="@";
   }  
   
   if(lenB>0){
   strB= b.substring(lenB-1);
   }
   else{
   strB="@";
   }   
   
     
  str= strA+strB;
  
    return str;
   
}

Open in new window


which passed the test. Please advise on how i can improve it
0
 
LVL 4

Expert Comment

by:Zsolt Pribusz
Comment Utility
You can improve your last code, if you definie strA and strB with "@" as starting value. In this case you don't need to use "else" in "if"s.
0
 
LVL 84

Expert Comment

by:ozo
Comment Utility
Or you can do it without StrA or StrB with a one liner and two ?: trinary operators instead of two if/else statements.
0
 
LVL 7

Author Comment

by:gudii9
Comment Utility
let me try
0
 
LVL 7

Author Comment

by:gudii9
Comment Utility
public String lastChars(String a, String b) {
int lenA=a.length();
int lenB=b.length();

String strA="";
String strB="";
String str="";
  if(lenA>0){
   strA= a.substring(0,1);
   }

   if(lenB>0){
   strB= b.substring(lenB-1);
   }
   
   
     
  str= strA+strB;
  
    return str;
   
}

Open in new window


i was able to remove else's from if successfully as above passsing all tests
0
 
LVL 7

Author Comment

by:gudii9
Comment Utility
public String lastChars(String a, String b) {
int lenA=a.length();
int lenB=b.length();

  
    return lenA>0 ? a.substring(0,1): b.substring(lenB-1);
   
}

Open in new window


i tried with ternary operator and failing all tests. How to fix or imprive my ternary code. please advise
0
 
LVL 31

Expert Comment

by:awking00
Comment Utility
You have not accounted for "@" replacing empty string values in a or b.
0
 
LVL 7

Author Comment

by:gudii9
Comment Utility
You have not accounted for "@" replacing empty string values in a or b.

are you referring to my comment ID: 40492054(how to copy comment as html link? bit off topic)
0
 
LVL 31

Expert Comment

by:awking00
Comment Utility
In order for you to fix your ternary code, you need to understand it. The ternary operator works in the following manner:
boolean condition ? value if condition is true : value if condition is false. In this challenge, there are four conditions available, lenA=0 or lenA>0 and lenB=0 or lenB>0 and you need values based on those being true or false. So in your ternary code, you have the condition lenA > 0 ? the value of a.substring(0,1) if condition is true, which is what you want (i.e. the first letter of string a) : but here you have the value of b.substring(lenB - 1) if condition is false, which is not what you want. If lenB is 0, you wll get the out of Bounds exception, otherwise you will get the last letter of str b. What I think you want when the conditon is false to get the String "@". That would take care of the two conditions for lenA and you could repeat the process for lenB which would involve two ternary statements.
0
 
LVL 31

Expert Comment

by:awking00
Comment Utility
>>are you referring to my comment ID: 40492054(how to copy comment as html link? bit off topic)<<
No, I was referring to your code in ID: 40492043 where you removed the else statements but didn't take care of the "@" requirement, which ZsoltPribusz pointed out could be done by instantiating strA and strB to "@".
0
 
LVL 7

Author Comment

by:gudii9
Comment Utility
public String lastChars(String a, String b) {
int lenA=a.length();
int lenB=b.length();

String strA="@";
String strB="@";
String str="";
  if(lenA>0){
   strA= a.substring(0,1);
   }

   if(lenB>0){
   strB= b.substring(lenB-1);
   }
   
   
     
  str= strA+strB;
  
    return str;
   
}

Open in new window


As above right
0
 
LVL 7

Author Comment

by:gudii9
Comment Utility
In order for you to fix your ternary code, you need to understand it. The ternary operator works in the following manner:
boolean condition ? value if condition is true : value if condition is false. In this challenge, there are four conditions available, lenA=0 or lenA>0 and lenB=0 or lenB>0 and you need values based on those being true or false. So in your ternary code, you have the condition lenA > 0 ? the value of a.substring(0,1) if condition is true, which is what you want (i.e. the first letter of string a) : but here you have the value of b.substring(lenB - 1) if condition is false, which is not what you want. If lenB is 0, you wll get the out of Bounds exception, otherwise you will get the last letter of str b. What I think you want when the conditon is false to get the String "@". That would take care of the two conditions for lenA and you could repeat the process for lenB which would involve two ternary statements.

public String lastChars(String a, String b) {
int lenA=a.length();
int lenB=b.length();

  
    return lenA>0 ? a.substring(0,1): "@";
    return lenB>0 ? b.substring(0,1): "@";
   
}

Open in new window


something like above. I was wrong in giving 2 return statements. But not getting idea to do better
0
 
LVL 84

Expert Comment

by:ozo
Comment Utility
If you want to try using ?: operators, perhaps it would help if you started by replacing the if statements in your working code in http:#a40491504
with exactly equivalent code using ?: operators in place of the if statements.
0
 
LVL 31

Expert Comment

by:awking00
Comment Utility
Ultimately the task is to return the first character of str a and the last character of str b with the caveat that, if either string has a length of 0, make them the character @. So, if str a is not empty (i.e. has a length of 0), then use a.substring(0,1) to find the first character. Likewiase, if str b is not empty (i.e. has a length of 0), then use b.substring(lenB - 1) to find the last character. Using the ternary operator, the first condition would be a.length() > 0 ? a.substring(0,1) => the value for a true conditon : "@" => the value for a false condition. The second condition would be b.length() > 0 ? b.substring(lenB - 1) => the value for a true conditon : "@" => the value for a false condition. You can then assign these ternary statements to variables, and return the concatenation of the two assigned values.
String strA = a.length() > 0 ? a.substring(0,1) : "@";
String strB = b.length() > 0 ? b.substring(lenB - 1);
return strA + strB;
0
 
LVL 35

Expert Comment

by:mccarl
Comment Utility
@awking00,

You might be missing your "false condition value" in the line for strB above.
0
 
LVL 7

Author Comment

by:gudii9
Comment Utility
public String lastChars(String a, String b) {

int lenA=a.length();
int lenB=b.length();

  
    String A=lenA>0 ? a.substring(0,1): "@";
    String B=lenB>0 ? b.substring(lenB-1): "@";
     return A+B;
     
    
   

   
}

Open in new window

i wrote as above and paased all tests. Does it looks fine.
Please advise
0
 
LVL 4

Expert Comment

by:Zsolt Pribusz
Comment Utility
It is fine. Everything in place.
Now if you want to go further, you can try to do this challenge without using "if" or ternary code.
0
 
LVL 7

Author Comment

by:gudii9
Comment Utility
How to do that. Please advise
0
 
LVL 84

Expert Comment

by:ozo
Comment Utility
You could transform the input strings in such a way as to make any "if" or ternary conditional tests unnecessary.

(probably not the method I would choose to use in this case since does more string construction, sometimes unnecessarily, but there can be occasions when avoiding conditional tests could make branch prediction pipelines more effective
And knowing how to approach a problem from different angles can be useful in programming)
0
 
LVL 4

Expert Comment

by:Zsolt Pribusz
Comment Utility
In this challenge, the input strings can be empty, and if this happens, you need to send back the "@" char instead the first or last char. If you merge input strings into one, and ensure that the "@" char appears at position in string where it need to be if input string is empty, then you don't need to do tests.
In this case maybe it produce faster code, but less informative to others.
0
 
LVL 7

Author Comment

by:gudii9
Comment Utility
public String lastChars(String a, String b) {

int lenA=a.length();
int lenB=b.length();

  
    String A=lenA>0 ? a.substring(0,1): "@";
    String B=lenB>0 ? b.substring(lenB-1): "@";
     return A+B;
     
    
   

   
}

Open in new window


i think we tried this approach right as above without if loop by using ternary operator. please advise
0
 
LVL 7

Author Comment

by:gudii9
Comment Utility
In this challenge, the input strings can be empty, and if this happens, you need to send back the "@" char instead the first or last char. If you merge input strings into one, and ensure that the "@" char appears at position in string where it need to be if input string is empty, then you don't need to do tests.
In this case maybe it produce faster code, but less informative to others.

i was not sure on how to do this. please advise
0
 
LVL 84

Expert Comment

by:ozo
Comment Utility
I don't know that it would produce faster code in this case, but one of the suggestions in the thread is an example of that.
0
Better Security Awareness With Threat Intelligence

See how one of the leading financial services organizations uses Recorded Future as part of a holistic threat intelligence program to promote security awareness and proactively and efficiently identify threats.

 
LVL 7

Author Comment

by:gudii9
Comment Utility
which suggestion. please advise
0
 
LVL 84

Expert Comment

by:ozo
Comment Utility
0
 
LVL 7

Author Comment

by:gudii9
Comment Utility
Ok
0
 
LVL 4

Expert Comment

by:Zsolt Pribusz
Comment Utility
You can create a merged sting like this:
NewString = FirstString + "@" + SecondString;

In this case, if FirstString is empty, then the NewSting will start with character "@", otherwise it will start with first character of FirstString. Also if Second string is empty, then the last character will be "@" in NewString. (Of course if SecondString isn't empty, then the last character of NewString will be the last character from SecondString).

If you constructed the new string like this, then it's length will be at least 1, so you don't need to do checks or error handling, you just need to return first and last char from this constructed string and you fullfilled the quest rules.
0
 
LVL 7

Author Comment

by:gudii9
Comment Utility
you mean like below
public String lastChars(String a, String b) {
int lenA=a.length();
int lenB=b.length();


 String FirstString =lenA>0 ? a.substring(0,1): "@";
 String SecondString =lenB>0 ? b.substring(lenB-1): "@";

String NewString = FirstString + "@" + SecondString;
//return (a+"@").substring(0,1) + ("@"+b).substring(b.length());
return NewString;
}

Open in new window


My testcases failing as extra @ coming. please advise
Expected	Run		
lastChars("last", "chars") → "ls"	"l@s"	X	    
lastChars("yo", "java") → "ya"	"y@a"	X	    
lastChars("hi", "") → "h@"	"h@@"	X	    
lastChars("", "hello") → "@o"	"@@o"	X	    
lastChars("", "") → "@@"	"@@@"	X	    
lastChars("kitten", "hi") → "ki"	"k@i"	X	    
lastChars("k", "zip") → "kp"	"k@p"	X	    
lastChars("kitten", "") → "k@"	"k@@"	X	    
lastChars("kitten", "zip") → "kp"	"k@p"	X	    
other tests
X	    

Open in new window

0
 
LVL 84

Expert Comment

by:ozo
Comment Utility
The proposal was for a method that did not use any ?: operators nor any if conditions.

http:#a40526103 adds an extra @ to a previously working solution.

One way to get from http:#a40526103 to the method proposed by Zsolt Pribusz could be to take NewString you created generate a correct return value from it.
(after that, you can then simplify the way NewString was created and avoid the conditionals)
0
 
LVL 7

Author Comment

by:gudii9
Comment Utility
public String lastChars(String a, String b) {
int lenA=a.length();
int lenB=b.length();


 String FirstString = a.substring(0,1);
 String SecondString =b.substring(lenB-1);

String NewString = FirstString + "@" + SecondString;
//return (a+"@").substring(0,1) + ("@"+b).substring(b.length());
return NewString;
}

Open in new window


even above is failing all tests. please advise
Expected	Run		
lastChars("last", "chars") → "ls"	"l@s"	X	    
lastChars("yo", "java") → "ya"	"y@a"	X	    
lastChars("hi", "") → "h@"	"Exception:java.lang.StringIndexOutOfBoundsException: String index out of range: -1 (line number:7)"	X	    
lastChars("", "hello") → "@o"	"Exception:java.lang.StringIndexOutOfBoundsException: String index out of range: 1 (line number:6)"	X	    
lastChars("", "") → "@@"	"Exception:java.lang.StringIndexOutOfBoundsException: String index out of range: 1 (line number:6)"	X	    
lastChars("kitten", "hi") → "ki"	"k@i"	X	    
lastChars("k", "zip") → "kp"	"k@p"	X	    
lastChars("kitten", "") → "k@"	"Exception:java.lang.StringIndexOutOfBoundsException: String index out of range: -1 (line number:7)"	X	    
lastChars("kitten", "zip") → "kp"	"k@p"	X	    
other tests
X	  

Open in new window

0
 
LVL 4

Expert Comment

by:Zsolt Pribusz
Comment Utility
You don't understand what I said.
This:
NewString = FirstString + "@" + SecondString;
was only an example.
To convert it to actual challange, then FirstString will be "a" and second string will be "b".
String NewString = a + "@" + b;

Open in new window

If you put this as first line in your program, then you don't need to care about length of "a" or "b" string, since the NewString will be at least 1 char length, and no error handling need. More over, in this case if you look at NewString first character it will be equal to string "a"s first character if "a" contains anything. If "a" string is empty, then NewString first character will be "@", the character what is expected to be returned if "a" string sis empty...
If you check this analogy with last character too, you will recognize why conditions not necessary, and you can do everything with newly constructed string.
0
 
LVL 7

Author Comment

by:gudii9
Comment Utility
If you put this as first line in your program, then you don't need to care about length of "a" or "b" string, since the NewString will be at least 1 char length, and no error handling need.

public String lastChars(String a, String b) {
// int lenA=a.length();
// int lenB=b.length();


// String FirstString = a.substring(0,1);
// String SecondString =b.substring(lenB-1);

// String NewString = FirstString + "@" + SecondString;
//return (a+"@").substring(0,1) + ("@"+b).substring(b.length());
String NewString =a+"@"+b;
return NewString;
}

Open in new window


i am failing all test cases. please advise
0
 
LVL 84

Expert Comment

by:ozo
Comment Utility
You still need to do something else with NewString to get the final answer.
0
 
LVL 7

Author Comment

by:gudii9
Comment Utility
public String lastChars(String a, String b) {
int lenA=a.length();
int lenB=b.length();

String strA="";
String strB="";
String str="";
  if(lenA>0){
   strA= a.substring(0,1);
   }

   if(lenB>0){
   strB= b.substring(lenB-1);
   }
   
   
     
  str= strA+strB;
  
    return str;
   
}

Open in new window

actually i made a mistake earlier. I thought above code passed all tests but it did fail few of them as below

"last", "chars") → "ls"	"ls"	OK	    
lastChars("yo", "java") → "ya"	"ya"	OK	    
lastChars("hi", "") → "h@"	"h"	X	    
lastChars("", "hello") → "@o"	"o"	X	    
lastChars("", "") → "@@"	""	X	    
lastChars("kitten", "hi") → "ki"	"ki"	OK	    
lastChars("k", "zip") → "kp"	"kp"	OK	    
lastChars("kitten", "") → "k@"	"k"	X	    
lastChars("kitten", "zip") → "kp"	"kp"	OK	    
other tests
X	    

Open in new window

Let me think
0
 
LVL 31

Expert Comment

by:awking00
Comment Utility
Why would you think that code would pass all tests when on of the requirements is to return an at sign ("@") in place of an empty string and there is no at sign anywhere within that code?

public String lastChars(String a, String b) {
int lenA=a.length();
int lenB=b.length();

String strA="";
String strB="";
String str="";
  if(lenA>0){
   strA= a.substring(0,1);
   }[b] else {
   strA = "@";
  }[/b]
   if(lenB>0){
   strB= b.substring(lenB-1);
   }[b] else {
   strB = "@";
  }[/b]
  str= strA+strB;
  
    return str;
}

Open in new window

0
 
LVL 31

Expert Comment

by:awking00
Comment Utility
Forget the characters inside the square brackets. I was trying to make the else statements that manage the "@" character bold, but I guess that can't be done within a code snippet.
0
 
LVL 7

Author Comment

by:gudii9
Comment Utility
public String lastChars(String a, String b) {
// int lenA=a.length();
// int lenB=b.length();


// String FirstString = a.substring(0,1);
// String SecondString =b.substring(lenB-1);

// String NewString = FirstString + "@" + SecondString;
return (a+"@").substring(0,1) + ("@"+b).substring(b.length());
//String NewString =a+"@"+b;
//return NewString;
}

Open in new window


above passes all tests

Expected	Run		
lastChars("last", "chars") → "ls"	"ls"	OK	    
lastChars("yo", "java") → "ya"	"ya"	OK	    
lastChars("hi", "") → "h@"	"h@"	OK	    
lastChars("", "hello") → "@o"	"@o"	OK	    
lastChars("", "") → "@@"	"@@"	OK	    
lastChars("kitten", "hi") → "ki"	"ki"	OK	    
lastChars("k", "zip") → "kp"	"kp"	OK	    
lastChars("kitten", "") → "k@"	"k@"	OK	    
lastChars("kitten", "zip") → "kp"	"kp"	OK	    
other tests

Open in new window


but not yet sure on what needs to be done in below approach suggested
You still need to do something else with NewString to get the final answer.
please advise
0
 
LVL 84

Expert Comment

by:ozo
Comment Utility
Since the above (http:#a40534146) code does not use NewString, comments regarding NewString are not relevant to it.
0
 
LVL 7

Author Comment

by:gudii9
Comment Utility
correct.

But how to use NewString and do as per
ID: 40526851

please advise
0
 
LVL 84

Expert Comment

by:ozo
Comment Utility
Let's pretend we had a new challenge to write a function that takes its input from the output of http:#a40533246
so that the new function returns the correct output for http://codingbat.com/prob/p138183
0
 
LVL 7

Author Comment

by:gudii9
Comment Utility
public class InputOutput {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		String s=lastChars("xyz","abc");
		String s2=lastCharsTwo("s");
		System.out.println("s is-->"+s);
		System.out.println("s2 is-->"+s2);

	}

	public static String lastChars(String a, String b) {
		// int lenA=a.length();
		// int lenB=b.length();


		// String FirstString = a.substring(0,1);
		// String SecondString =b.substring(lenB-1);

		// String NewString = FirstString + "@" + SecondString;
		//return (a+"@").substring(0,1) + ("@"+b).substring(b.length());
		String NewString =a+"@"+b;
		return NewString;
		}
	
	
//	Let's pretend we had a new challenge to write a function that takes its input from the output of http:#a40533246
//	so that the new function returns the correct output for http://codingbat.com/prob/p138183
	

	/*Given 2 strings, a and b, return a new string made of the first char of a and the last char of b, so "yo" and "java" yields "ya". If either string is length 0, use '@' for its missing char. 

	lastChars("last", "chars") → "ls"
	lastChars("yo", "java") → "ya"
	lastChars("hi", "") → "h@"*/
	
	public static String lastCharsTwo(String NewString) {
		// int lenA=a.length();
		// int lenB=b.length();


		// String FirstString = a.substring(0,1);
		// String SecondString =b.substring(lenB-1);

		// String NewString = FirstString + "@" + SecondString;
		//return (a+"@").substring(0,1) + ("@"+b).substring(b.length());
		String NewString3 =NewString;
		return NewString3;
		}
	
}

Open in new window


something like above. I do not see my sysouts priniting any thing. please advise
0
 
LVL 7

Author Comment

by:gudii9
Comment Utility
Let's pretend we had a new challenge to write a function that takes its input from the output of http:#a40533246
so that the new function returns the correct output for http://codingbat.com/prob/p138183
Do you mean like below

public class InputOutput {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		String s=lastChars("xyz","abc");
	
		String s2=lastCharsTwo(s);
		System.out.println("s is-->"+s);
		System.out.println("s2 is-->"+s2);

	}

	public static String lastChars(String a, String b) {
		// int lenA=a.length();
		int lenB=b.length();


		// String FirstString = a.substring(0,1);
		// String SecondString =b.substring(lenB-1);

		// String NewString = FirstString + "@" + SecondString;
		//return (a+"@").substring(0,1) + ("@"+b).substring(b.length());
		String NewString =a.substring(0, 1)+"@"+b.substring(lenB-1, lenB);
		return NewString;
		}
	
	
//	Let's pretend we had a new challenge to write a function that takes its input from the output of http:#a40533246
//	so that the new function returns the correct output for http://codingbat.com/prob/p138183
	

	/*Given 2 strings, a and b, return a new string made of the first char of a and the last char of b, so "yo" and "java" yields "ya". If either string is length 0, use '@' for its missing char. 

	lastChars("last", "chars") → "ls"
	lastChars("yo", "java") → "ya"
	lastChars("hi", "") → "h@"*/
	
	public static String lastCharsTwo(String NewString) {
		// int lenA=a.length();
		// int lenB=b.length();


		// String FirstString = a.substring(0,1);
		// String SecondString =b.substring(lenB-1);

		// String NewString = FirstString + "@" + SecondString;
		//return (a+"@").substring(0,1) + ("@"+b).substring(b.length());
		String NewString3 =NewString;
		return NewString3;
		}
	
}

Open in new window


please advise
0
 
LVL 84

Expert Comment

by:ozo
Comment Utility
http:#a40533246 does this:
lastChars("last", "chars") → "ls"      "last@chars"      X         
lastChars("yo", "java") → "ya"      "yo@java"      X         
lastChars("hi", "") → "h@"      "hi@"      X         
lastChars("", "hello") → "@o"      "@hello"      X         
lastChars("", "") → "@@"      "@"      X         
lastChars("kitten", "hi") → "ki"      "kitten@hi"      X         
lastChars("k", "zip") → "kp"      "k@zip"      X         
lastChars("kitten", "") → "k@"      "kitten@"      X         
lastChars("kitten", "zip") → "kp"       "kitten@zip"

Can you fix it with a function that does this?
"last@chars" → "ls"
"yo@java" → "ya"         
"hi@" → "h@"
"@hello" → "@o"       
"@" → "@@"                
"kitten@hi" → "ki"      
"k@zip"  → "kp"      
"kitten@" → "k@"      
"kitten@zip" → "kp"
0
 
LVL 7

Author Comment

by:gudii9
Comment Utility
public String lastChars(String a, String b) {
// int lenA=a.length();
// int lenB=b.length();


// String FirstString = a.substring(0,1);
// String SecondString =b.substring(lenB-1);

// String NewString = FirstString + "@" + SecondString;
return (a+"@").substring(0,1) + ("@"+b).substring(b.length());
//String NewString =a+"@"+b;
//return NewString;
}

Open in new window


above code approach is producing desired result right as below

"last@chars" → "ls"
"yo@java" → "ya"          
"hi@" → "h@"
"@hello" → "@o"        
"@" → "@@"                
"kitten@hi" → "ki"      
"k@zip"  → "kp"      
"kitten@" → "k@"      
"kitten@zip" → "kp"


Now you are mentioning about second approach right something like below

public class InOut2 {

	
	 /*http:#a40533246 does this:
lastChars("last", "chars") → "ls"      "last@chars"      X          
lastChars("yo", "java") → "ya"      "yo@java"      X          
lastChars("hi", "") → "h@"      "hi@"      X          
lastChars("", "hello") → "@o"      "@hello"      X          
lastChars("", "") → "@@"      "@"      X          
lastChars("kitten", "hi") → "ki"      "kitten@hi"      X          
lastChars("k", "zip") → "kp"      "k@zip"      X          
lastChars("kitten", "") → "k@"      "kitten@"      X          
lastChars("kitten", "zip") → "kp"       "kitten@zip"

Can you fix it with a function that does this?
"last@chars" → "ls"
"yo@java" → "ya"          
"hi@" → "h@"
"@hello" → "@o"        
"@" → "@@"                
"kitten@hi" → "ki"      
"k@zip"  → "kp"      
"kitten@" → "k@"      
"kitten@zip" → "kp"*/
	 
	public static void main(String[] args) {
		// TODO Auto-generated method stub

	}
	public String lastChars(String a, String b) {
		// int lenA=a.length();
		// int lenB=b.length();


		// String FirstString = a.substring(0,1);
		// String SecondString =b.substring(lenB-1);

		// String NewString = FirstString + "@" + SecondString;
		//return (a+"@").substring(0,1) + ("@"+b).substring(b.length());
		String NewString =a+"@"+b;
		return NewString;
		}
}

Open in new window


I still do not get any idea how to proceed on this. please advise
0
 
LVL 31

Expert Comment

by:awking00
Comment Utility
Why do you think you need to proceed with that concept? Ever consider that it might not work?
0
 
LVL 7

Author Comment

by:gudii9
Comment Utility
i was trying to find and learn any other alternative ways of doing this challenge.
0
 
LVL 84

Expert Comment

by:ozo
Comment Utility
Zsolt Pribusz suggested a method to do
"last@chars" → "ls"
"yo@java" → "ya"          
"hi@" → "h@"
"@hello" → "@o"        
"@" → "@@"                
"kitten@hi" → "ki"      
"k@zip"  → "kp"      
"kitten@" → "k@"      
"kitten@zip" → "kp"
in the post on http:#a40517955
0
 
LVL 31

Expert Comment

by:awking00
Comment Utility
>>i was trying to find and learn any other alternative ways of doing this challenge<<
The approach Zsolt Pribusz gave of using a new string of a + "@" + b to create a result that meets the challenge is certainly another alternative. It's just that he didn't supply the final code although provided the concept in the narrative, hoping you would be able to complete the challenge. The narrative concept provided was "you just need to return first and last char from this constructed string" so the final code would look something like this -
String newString = a + "@" + b;
 return newString.substring(0, 1) + newString.substring(newString.length() - 1);
0
 
LVL 84

Expert Comment

by:ozo
Comment Utility
Indeed, that passes all tests.
0
 
LVL 7

Author Comment

by:gudii9
Comment Utility
public String lastChars(String a, String b) {
// int lenA=a.length();
// int lenB=b.length();


// String FirstString = a.substring(0,1);
// String SecondString =b.substring(lenB-1);

// String NewString = FirstString + "@" + SecondString;
//return (a+"@").substring(0,1) + ("@"+b).substring(b.length());
//String NewString =a+"@"+b;
//return NewString;



String newString = a + "@" + b;
 return newString.substring(0, 1) + newString.substring(newString.length()-1);
}

Open in new window


i got second approach as above where i am passing all the tests now.
0
 
LVL 7

Author Comment

by:gudii9
Comment Utility
return newString.substring(0, 1) + newString.substring(newString.length() - 1);

what is the meaning of above code how it is passing all the tests esp when a or b is null.

please advise
0
 
LVL 84

Expert Comment

by:ozo
Comment Utility
When a and b are null,  newString = "" + "@" + "";  becomes newString = "@";
0
 
LVL 7

Author Comment

by:gudii9
Comment Utility
When a and b are null,  newString = "" + "@" + "";  becomes newString = "@";

is this is requirement?
please advise
0
 
LVL 7

Author Comment

by:gudii9
Comment Utility
public String lastChars(String a, String b) {

a=null;
String as=a+"@";
String bs="@"+b;

return as.substring(0,1)+bs.substring(bs.length()-1);
  
}

Open in new window


when i wrote like that and tested n in the null is taken some reason wrongly. Please advise
0
 
LVL 84

Expert Comment

by:ozo
Comment Utility
a=null;
is being interpreted by java as
a="null";


I interpreted your use of the word null in http:#a40564962 to mean empty
in which case newString = "@"; would be a requirement of Zsolt Pribusz's method for evaluating lastChars("", "")
0
 
LVL 7

Author Comment

by:gudii9
Comment Utility
public String lastChars(String a, String b) {

a=null;
b=null;
String as=a+"@";
String bs="@"+b;

return as.substring(0,1)+bs.substring(bs.length()-1);
  
}

Open in new window


when i wrote as above got tests failed due to weird results.

Expected	Run		
lastChars("last", "chars") → "ls"	"nl"	X	    
lastChars("yo", "java") → "ya"	"nl"	X	    
lastChars("hi", "") → "h@"	"nl"	X	    
lastChars("", "hello") → "@o"	"nl"	X	    
lastChars("", "") → "@@"	"nl"	X	    
lastChars("kitten", "hi") → "ki"	"nl"	X	    
lastChars("k", "zip") → "kp"	"nl"	X	    
lastChars("kitten", "") → "k@"	"nl"	X	    
lastChars("kitten", "zip") → "kp"	"nl"	X	    
other tests
X	  

Open in new window

0
 
LVL 7

Author Comment

by:gudii9
Comment Utility
public String lastChars(String a, String b) {

a="null";
b="null";
String as=a+"@";
String bs="@"+b;

return as.substring(0,1)+bs.substring(bs.length()-1);
  
}

Open in new window

when i modified as above still failied
Expected	Run		
lastChars("last", "chars") → "ls"	"nl"	X	    
lastChars("yo", "java") → "ya"	"nl"	X	    
lastChars("hi", "") → "h@"	"nl"	X	    
lastChars("", "hello") → "@o"	"nl"	X	    
lastChars("", "") → "@@"	"nl"	X	    
lastChars("kitten", "hi") → "ki"	"nl"	X	    
lastChars("k", "zip") → "kp"	"nl"	X	    
lastChars("kitten", "") → "k@"	"nl"	X	    
lastChars("kitten", "zip") → "kp"	"nl"	X	    
other tests
X	    
Your progress graph for this problem

Open in new window

0
 
LVL 7

Author Comment

by:gudii9
Comment Utility
public String lastChars(String a, String b) {

a="";
b="";
String as=a+"@";
String bs="@"+b;

return as.substring(0,1)+bs.substring(bs.length()-1);
  
}

Open in new window


above passed one test as expected though.
Expected	Run		
lastChars("last", "chars") → "ls"	"@@"	X	    
lastChars("yo", "java") → "ya"	"@@"	X	    
lastChars("hi", "") → "h@"	"@@"	X	    
lastChars("", "hello") → "@o"	"@@"	X	    
lastChars("", "") → "@@"	"@@"	OK	    
lastChars("kitten", "hi") → "ki"	"@@"	X	    
lastChars("k", "zip") → "kp"	"@@"	X	    
lastChars("kitten", "") → "k@"	"@@"	X	    
lastChars("kitten", "zip") → "kp"	"@@"	X	    
other tests
X

Open in new window

0
 
LVL 84

Expert Comment

by:ozo
Comment Utility
Both as expected.

a=null;
was interpreted by java as
a="null";
0
 
LVL 31

Expert Comment

by:awking00
Comment Utility
public String lastChars(String a, String b) {

a="";   ==>  You've taken your input parameters and set them to null so you'll always return @@
b="";   ==>  Remove these two lines
String as=a+"@";
String bs="@"+b;

return as.substring(0,1)+bs.substring(bs.length()-1);
 
}
0
 
LVL 7

Author Comment

by:gudii9
Comment Utility
a=null;
was interpreted by java as
a="null";

how to assign null to a string?
0
 
LVL 7

Author Comment

by:gudii9
Comment Utility
String a=null

seems taken as
String a="null"


I know string by default takes null for undeclared string objects. Still i wonder is there is a way to assing null to a string object.
Please advise
0
 
LVL 7

Author Comment

by:gudii9
Comment Utility
Please advise
0
 
LVL 84

Expert Comment

by:ozo
Comment Utility
What purpose are you trying to achieve by assigning a null to a string object?
0
 
LVL 7

Author Comment

by:gudii9
Comment Utility
just some theoritical interest. While do ing some trial and error i bumped into this issue. I wonder how to assign null in this case if at all it is possible?
0
 
LVL 84

Expert Comment

by:ozo
Comment Utility
String object;

but then, if you try to do anything with it before assigning an actual value to it, for example by saying
return object;
you get
error:      return object;
             ^^^^^^
The local variable object may not have been initialized
0
 
LVL 7

Author Comment

by:gudii9
Comment Utility
String object;

but then, if you try to do anything with it before assigning an actual value to it, for example by saying
return object;
you get
error:      return object;
             ^^^^^^

That is reason i want to assign to null saying
String object=null;
which seems kind of meaninglesss but wonder why it is treated as "null" by java rather than giving say null pointer etc. please advise
0
 
LVL 84

Accepted Solution

by:
ozo earned 167 total points
Comment Utility
You want to avoid "The local variable object may not have been initialized" error, you can do it by initializing
String object = "Ceci n'est pas une null";
0
 
LVL 7

Author Comment

by:gudii9
Comment Utility
ok

String object = "Ceci n'est pas une null";

inside "" i can give anything right
0

Featured Post

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

Entering a date in Microsoft Access can be tricky. A typo can cause month and day to be shuffled, entering the day only causes an error, as does entering, say, day 31 in June. This article shows how an inputmask supported by code can help the user a…
Although it can be difficult to imagine, someday your child will have a career of his or her own. He or she will likely start a family, buy a home and start having their own children. So, while being a kid is still extremely important, it’s also …
This video teaches viewers about errors in exception handling.
The viewer will learn how to user default arguments when defining functions. This method of defining functions will be contrasted with the non-default-argument of defining functions.

771 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

9 Experts available now in Live!

Get 1:1 Help Now