conCat challenge

Hi,

I am working on below challenge
http://codingbat.com/prob/p132118
I wrote my code as below
public String conCat(String a, String b) {
String str="";
int aLength=a.length()-1;
int bLength=b.length()-1;

if(a.substring(aLength)==(b.substring(0,1)))
{
  str=(a.substring(0,aLength-3))+(b.substring(0));
  }
  else
  {
  str=a+b;
  }
  return str;
}

Open in new window

I am failing below tests.


Expected	Run		
conCat("abc", "cat") → "abcat"	"abccat"	X	    
conCat("dog", "cat") → "dogcat"	"dogcat"	OK	    
conCat("abc", "") → "abc"	"Exception:java.lang.StringIndexOutOfBoundsException: String index out of range: 1 (line number:6)"	X	    
conCat("", "cat") → "cat"	"Exception:java.lang.StringIndexOutOfBoundsException: String index out of range: -1 (line number:6)"	X	    
conCat("pig", "g") → "pig"	"pigg"	X	    
conCat("pig", "doggy") → "pigdoggy"	"pigdoggy"	OK	    
other tests

Open in new window

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.

firebeastCommented:
Can you think of a way to compare the 2 middle characters, and remove one if they are the same?
0
gudii9Author Commented:
public class Test38 {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		String strFinal=conCat("abc","cef");
		System.out.println("string is -->"+strFinal);
	}

	public static String conCat(String a, String b) {
		String str="";
		int aLength=a.length();
		int bLength=b.length();
System.out.println("last of a is--"+a.substring(a.length()-1));
System.out.println("first of b is--"+b.substring(0,1));
System.out.println("firstttt of a is--"+a.substring(0));
System.out.println("firsttttt of b is--"+b.substring(1,bLength-1));
		if(a.substring(a.length()-1)==(b.substring(0,1)))
		{
			System.out.println("in if loop");
		  str=(a.substring(0)+(b.substring(1,bLength-1)));//complete 1st then 2nd from index 1 to last
		  }
		  else
		  {
			  System.out.println("in else loop");
		  str=a+b;
		  }
		  return str;
		}
}

Open in new window


i tried as above. some how going in else loop not in if loop.

please advise
0
gudii9Author Commented:
public class Test38 {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		String strFinal=conCat("abc","cef");
		System.out.println("string is -->"+strFinal);
	}

	public static String conCat(String a, String b) {
		String str="";
		int aLength=a.length();
		int bLength=b.length();
System.out.println("last of a is--"+a.substring(a.length()-1));
System.out.println("first of b is--"+b.substring(0,1));
System.out.println("firstttt of a is--"+a.substring(0));
System.out.println("firsttttt of b is--"+b.substring(1,bLength-1));
		if(a.substring(a.length()-1).equals((b.substring(0,1))))
		{
			System.out.println("in if loop");
		  str=(a.substring(0)+(b.substring(1,bLength)));//complete 1st then 2nd from index 1 to last
		  }
		  else
		  {
			  System.out.println("in else loop");
		  str=a+b;
		  }
		  return str;
		}
}

Open in new window


when i write with .equals went inside if loop (not when i used ==. i wonder why)

also
b.substring(1,bLength) givining desired result(i thought b.substring(1,bLength-1 should give desired result)
please advise
0
The Ultimate Tool Kit for Technolgy Solution Provi

Broken down into practical pointers and step-by-step instructions, the IT Service Excellence Tool Kit delivers expert advice for technology solution providers. Get your free copy for valuable how-to assets including sample agreements, checklists, flowcharts, and more!

ozoCommented:
When aLength==0, a.substring(a.length()-1) is an invalid operation
When bLength==0, b.substring(0,1) is an invalid operation
0
ozoCommented:
When used on String objects, == is true when two references are to the same object
equals is true when the values contained in the two objects are identical.
0
zzynxSoftware engineerCommented:
First, you have to check for these corner cases.
1) both strings being empty [ if (aLength<0 && bLength<0) ] => return an empty string
2) the first string being empty [ else if (aLength<0) ]=> return the second string
3) the second string being empty [ else if (bLength<0) ]=> return the first string

Then do the normal processing:
4) the last character of the first string is the same as the first character as the second string
[ if (a.substring(aLength).equals(b.substring(0,1))) ]
=> return the first string + all characters of the  second string except the first character
5) if not all of the above cases [ else ]: return first string + second string

If you program the above flow, all test cases become green.
0
ozoCommented:
If zzynx means ==0 instead of <0, then case 2) adequately covers case 1)
0
zzynxSoftware engineerCommented:
Since the author already has defined
int aLength=a.length()-1;
int bLength=b.length()-1;

Open in new window

I really mean <0

PS.
This is in fact a good example of bad variable names ;-)
I would rather call 'em 'aIndex' and 'bIndex'
0
ozoCommented:
I guess it depends on which of  the authors code samples you take the definitions from.
I agree with the point about unclear variable names.
0
gudii9Author Commented:
corner cases before normal processing is good approach which i am missing. Let me re read few times to get it
0
gudii9Author Commented:
1) both strings being empty [ if (aLength<0 && bLength<0)

if (aLength<0 && bLength<0)---> if(true&&true) comes right since if(0<0&&0<0)

0 cannot be less than 0 right (it can only be equal)
Please advise
0
zzynxSoftware engineerCommented:
If your first string is "".
aLength defined as a.length()-1 will be -1.
So,
if (aLength<0 && bLength<0) means: first ànd second string are BOTH empty

PS.
>> ...comes right since if(0<0&&0<0)
Wrong!
(0<0) is always false
(0<=0) is always true
(0>=0) is always true
(0>0) is always false
(-1<0) is always true
0
ozoCommented:
corner cases before normal processing
Often, (though perhaps less so for this challenge than some others) one can transform the corner cases in such a way that they will be correctly handled by normal processing.
Alternatively, one might bypass the normal processing after dealing with a corner case.
But even without explicit corner cases, it can be helpful to check that your processing is properly handling its edge cases.
0
gudii9Author Commented:
are edge cases different from corner cases. Or both essentially means same?
0
ozoCommented:
In informal speech, they might be used interchangeably.
In some contexts, one may want to distinguish a corner as a place where two edges meet.
0
zzynxSoftware engineerCommented:
>> Often, one can transform the corner cases in such a way that they will be correctly handled by normal processing.
No doubt that is (always) possible.
But in my opinion, in a lot of cases it is much better for the readability and hence the maintainability of the code to process them separately. The normal processing becomes easier and you clearly see that the special corner cases are taken care of. If you process all cases in one process block, you have to take a deeper/closer look to check that the corner cases are dealt with.
That's the eternal trade off between dense code versus readable code. I prefer the last one for sure.
0
ozoCommented:
take a deeper/closer look to check that the corner cases are dealt with
A good precaution even when corner cases are not explicitly presented.
0
gudii9Author Commented:
any good articles links books on these topics. I was not very familiar on these edge, corner, normal etc cases.

Please advise
0
zzynxSoftware engineerCommented:
Checking that the corner cases are dealt with is indeed a good thing to do, if not a must.
My point is that checking that, is much easier when those corner cases are processed in separate blocks.
Especially in code that someone else wrote. Which is the case (daily) when you work in a software team.
0
zzynxSoftware engineerCommented:
I don't know articles about corner/normal cases.

But the goal of processing them separately is:
of which I quote:
Optimise for the reader of the code, not the writer. Code is read more than it's written. If you optimise for the writer, you'll save a few key presses, but the cost to the reader is confusion, frustration, and subtle (and not-so-subtle) bugs.


0
gudii9Author Commented:
public class Test38 {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		String strFinal=conCat("abc","cef");
		//System.out.println("string is -->"+strFinal);
	}

	public static String conCat(String a, String b) {
		String str="";
		int aLength=a.length();
		int bLength=b.length();
//System.out.println("last of a is--"+a.substring(a.length()-1));
//System.out.println("first of b is--"+b.substring(0,1));
//System.out.println("firstttt of a is--"+a.substring(0));
//System.out.println("firsttttt of b is--"+b.substring(1,bLength-1));
		if(a.substring(a.length()-1).equals((b.substring(0,1))))
		{
			//System.out.println("in if loop");
		  str=(a.substring(0)+(b.substring(1,bLength)));//complete 1st then 2nd from index 1 to last
		  }
		  else
		  {
			 // System.out.println("in else loop");
		  str=a+b;
		  }
		  return str;
		}
}

Open in new window


i tried as above still not passing all. Let me remove system outs and try in coding bat site.please advise on how to fix
0
gudii9Author Commented:

      public String conCat(String a, String b) {
            String str="";
            int aLength=a.length();
            int bLength=b.length();

            if(a.substring(a.length()-1).equals((b.substring(0,1))))
            {
                  
              str=(a.substring(0)+(b.substring(1,bLength)));//complete 1st then 2nd from index 1 to last
              }
              else
              {
                  
              str=a+b;
              }
              return str;
            }

i am failing in two test cases.

xpected	Run		
conCat("abc", "cat") → "abcat"	"abcat"	OK	    
conCat("dog", "cat") → "dogcat"	"dogcat"	OK	    
conCat("abc", "") → "abc"	"Exception:java.lang.StringIndexOutOfBoundsException: String index out of range: 1 (line number:7)"	X	    
conCat("", "cat") → "cat"	"Exception:java.lang.StringIndexOutOfBoundsException: String index out of range: -1 (line number:7)"	X	    
conCat("pig", "g") → "pig"	"pig"	OK	    
conCat("pig", "doggy") → "pigdoggy"	"pigdoggy"	OK	    
other tests
OK	  

Open in new window


please advise
0
ozoCommented:
The tests that are not passing are the case when aLength == 0 and  the case when bLength == 0
Some of the operations you are performing are invalid in such cases.
0
gudii9Author Commented:
I see i forgot the edge cases
	public String conCat(String a, String b) {
		String str="";
		int aLength=a.length();
		int bLength=b.length();

		if(aLength>0&& bLength>0&& a.substring(a.length()-1).equals((b.substring(0,1))))
		{
			
		  str=(a.substring(0)+(b.substring(1,bLength)));//complete 1st then 2nd from index 1 to last
		  }
		  else
		  {
			
		  str=a+b;
		  }
		  return str;
		}

Open in new window


above passed all test cases. All looks fine right? please advise
0
ozoCommented:
Much better, though I personally prefer indentation proportional to depth of nesting.
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.