java string challenge issue

Hi,

I tried below example
http://codingbat.com/prob/p143825

I wrote like below
public String nonStart(String a, String b) {
StringBuilder sb1=null;
String aFirst=null;
String bFirst=null;
  if(a.length()>1&&b.length()>1){
  aFirst=a.substring(1,a.length());
    bFirst=b.substring(1,b.length());
  return aFirst+bFirst;
  
  }
  return null;
}

Open in new window

it is pasing some and failing in some test cases

Expected	Run		
nonStart("Hello", "There") → "ellohere"	"ellohere"	OK	    
nonStart("java", "code") → "avaode"	"avaode"	OK	    
nonStart("shotl", "java") → "hotlava"	"hotlava"	OK	    
nonStart("ab", "xy") → "by"	"by"	OK	    
nonStart("ab", "x") → "b"	"null"	X	    
nonStart("x", "ac") → "c"	"null"	X	    
nonStart("a", "x") → ""	"null"	X	    
nonStart("kit", "kat") → "itat"	"itat"	OK	    
nonStart("mart", "dart") → "artart"	"artart"	OK	    
other tests
X	

Open in new window

please advise on 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.

Vsevolod GeraskinCommented:
Please try a quick solution below.

public String nonStart(String a, String b) {
  String result="";
  String aFirst=null;
  String bFirst=null;
  
  if(a.length()>1) result=a.substring(1,a.length());
  if(b.length()>1) result+=b.substring(1,b.length());
  
  return result;
}

Open in new window


If you initialize result to null instead, you will need a null check as well.
0
mccarlIT Business Systems Analyst / Software DeveloperCommented:
Because they specify a constraint that the lengths of the strings will be at least 1, you can simply do this...
public String nonStart(String a, String b) {
  return a.substring(1) + b.substring(1);
}

Open in new window


You don't need to specify the length of the substring because there are 2 versions of substring, one that takes the 2 parameters that you are using, and one that takes only 1 parameter, and just returns the remaining part of the original string from whatever index that you specify. It even works for a string that is only 1 character long, it just returns the empty string (you may remember that we looked at this in a previous question of yours)
0
ozoCommented:
What is the purpose of the test on line 5?
0
Cloud Class® Course: Amazon Web Services - Basic

Are you thinking about creating an Amazon Web Services account for your business? Not sure where to start? In this course you’ll get an overview of the history of AWS and take a tour of their user interface.

gudii9Author Commented:
I am realizing line 5 is not needed based on above comments.
public String nonStart(String a, String b) {
  String result="";
  String aFirst=null;
  String bFirst=null;
  
  if(a.length()>1) result=a.substring(1,a.length());
  if(b.length()>1) result+=b.substring(1,b.length());
  
  return result;
}

Open in new window


In the above code I see aFirst and bFirst are declared as null where as result is empty string within double quotes. I wonder why it is different in case of result?
  String result="";
  String aFirst=null;
  String bFirst=null;

when i write as below by defining aFirst and bFirst as "" similar to result all tests passed.
public String nonStart(String a, String b) {
  String result="";
  String aFirst="";
  String bFirst="";
 
  if(a.length()>1) result=a.substring(1,a.length());
  if(b.length()>1) result+=b.substring(1,b.length());
 
  return result;
}

when i wrote all three variables as null as below then few test cases failied
public String nonStart(String a, String b) {
  String result=null;
  String aFirst=null;
  String bFirst=null;
  
  if(a.length()>1) result=a.substring(1,a.length());
  if(b.length()>1) result+=b.substring(1,b.length());
  
  return result;
}

Open in new window


test case results
Expected	Run		
nonStart("Hello", "There") → "ellohere"	"ellohere"	OK	    
nonStart("java", "code") → "avaode"	"avaode"	OK	    
nonStart("shotl", "java") → "hotlava"	"hotlava"	OK	    
nonStart("ab", "xy") → "by"	"by"	OK	    
nonStart("ab", "x") → "b"	"b"	OK	    
nonStart("x", "ac") → "c"	"nullc"	X	    
nonStart("a", "x") → ""	"null"	X	    
nonStart("kit", "kat") → "itat"	"itat"	OK	    
nonStart("mart", "dart") → "artart"	"artart"	OK	    
other tests
OK	  

Open in new window

0
Vsevolod GeraskinCommented:
You still need to initialize result to an empty string at some point, since one of the conditions is an empty string rather than null: nonStart("a", "x") → "";
public String nonStart(String a, String b) {
  String result=null;
  String aFirst=null;
  String bFirst=null;
  
  if(a.length()>1) {
    result=a.substring(1,a.length());
  } else {
    result = "";
  }
  
  if(b.length()>1) result+=b.substring(1,b.length());

  
  return result;

}

Open in new window

0
awking00Commented:
public String nonStart(String a, String b) {
if (a.length() == 1 && b.length() > 1) {
 return b.substring(1,b.length())
{ else if (a.length() == 1 && b.length() > 1) {
 return a.substring(1,a.length())
} else if (a.length() > 1 && b.length() > 1) {
 return a.substring(1,a.length()) + b.substring(1,b.length())
}
return null;
}
0
gudii9Author Commented:
public String nonStart(String a, String b) {
  String result=null;
  String aFirst=null;
  String bFirst=null;
  
  if(a.length()>1) {
  result=a.substring(1,a.length());
  }
  else{
  
  return "";
  }
  if(b.length()>1) {
  result+=b.substring(1,b.length());
  }
 
  return result;
}

Open in new window


i wrote as above still failing one test cases as below. please advise
Expected	Run		
nonStart("Hello", "There") → "ellohere"	"ellohere"	OK	    
nonStart("java", "code") → "avaode"	"avaode"	OK	    
nonStart("shotl", "java") → "hotlava"	"hotlava"	OK	    
nonStart("ab", "xy") → "by"	"by"	OK	    
nonStart("ab", "x") → "b"	"b"	OK	    
nonStart("x", "ac") → "c"	""	X	    
nonStart("a", "x") → ""	""	OK	    
nonStart("kit", "kat") → "itat"	"itat"	OK	    
nonStart("mart", "dart") → "artart"	"artart"	OK	    
other tests
OK	    

Open in new window

0
ozoCommented:
awking00: Did you actually try that?
0
ozoCommented:
gudii9: Do yo see the difference between  return ""; and result = "";?
0
gudii9Author Commented:
No. Both looks same to me
0
ozoCommented:
They don't look the same to java
nonStart("x", "ac") → "c"      ""      X      
nonStart("x", "ac") → "c"      "c"      OK
0
gudii9Author Commented:
I still do not see the difference what java is seeing. when i run as below

public class Test31 {

      /**
       * @param args
       */
      public static void main(String[] args) {
            // TODO Auto-generated method stub
            String str1=nonStart("x", "ac");    
            String str2=nonStart("x", "ac");
            System.out.println("str1 is"+str1);
            System.out.println("str2 is"+str2);

      }
      
      public static String nonStart(String a, String b) {
              String result=null;
              String aFirst=null;
              String bFirst=null;
             
              if(a.length()>1) {
              result=a.substring(1,a.length());
              }
              else{
             
              return "";
              }
              if(b.length()>1) {
              result+=b.substring(1,b.length());
              }
             
              return result;
            }


}

i got output as below
str1 is
str2 is   //here i expected to see "c" as per your above comment but failed to see that and got same output as above line

Does it mean eclipse also thinking like me not the java way?
Please advise
0
awking00Commented:
guidii9
The method nonStart(String a, String b) is going to return the same value every time, as it should, no matter how many variables you assign it to. In your example, you're passing in values of "x" and "ac" and assigning the return value to two variables, str1 and str2. In your method, the first if statement says "if the length of String a (i.e. "x") is greater than 1 then return a.substring(1, a.length()) and, if not return "" (i.e. an empty string). Since the length of "x" is not greater than 1, it returns the empty string. Once your method returns a value, it is done and doesn't evaluate any expressions that follow. Therefore, any time the first parameter has a length of 1, it will always return the empty string.

ozo,
Yes, I did but without the copy and paste error :-) It was supposed to be -
public String nonStart(String a, String b) {
if (a.length() == 1 && b.length() > 1) {
 return b.substring(1,b.length())
{ else if (a.length() > 1 && b.length() == 1) {
 return a.substring(1,a.length())
} else if (a.length() > 1 && b.length() > 1) {
 return a.substring(1,a.length()) + b.substring(1,b.length())
}
return null;
}
0
gudii9Author Commented:
public class Test31 {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		String str1 = nonStart("x", "ac");
		String str2 = nonStart("x", "ac");
		System.out.println("str1 is" + str1);
		System.out.println("str2 is" + str2);

	}

	public static String nonStart(String a, String b) {
		if (a.length() == 1 && b.length() > 1) {
			
		}
		 return b.substring(1,b.length())
		{ else if (a.length() > 1 && b.length() == 1) {
		 return a.substring(1,a.length())
		} else if (a.length() > 1 && b.length() > 1) {
		 return a.substring(1,a.length()) + b.substring(1,b.length())
		}
		return null;
		}
}
}

Open in new window


above giving error as
Exception in thread "main" java.lang.Error: Unresolved compilation problem:

      at Test31.main(Test31.java:7)


please advise
0
ozoCommented:
Test31.java:19: ';' expected
		 return b.substring(1,b.length())
		                                 ^
Test31.java:20: 'else' without 'if'
		{ else if (a.length() > 1 && b.length() == 1) {
		  ^
Test31.java:21: ';' expected
		 return a.substring(1,a.length())
		                                 ^
Test31.java:23: ';' expected
		 return a.substring(1,a.length()) + b.substring(1,b.length())
		                                                             ^

Open in new window

0
awking00Commented:
public static String nonStart(String a, String b) {
            if (a.length() == 1 && b.length() > 1) {
           Nothing is being done within the curly brackets      
            } => This closing bracket needs to be moved to before the next else if section replacing the opening bracket that exists there now, see below remove this bracket statement

             return b.substring(1,b.length())
remove this bracket =>{ else if (a.length() > 1 && b.length() == 1) {
             return a.substring(1,a.length())
            } else if (a.length() > 1 && b.length() > 1) {
             return a.substring(1,a.length()) + b.substring(1,b.length())
            }
            return null;
            }
0
gudii9Author Commented:
public class Test31 {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		String str1 = nonStart("x", "ac");
		String str2 = nonStart("x", "ac");
		System.out.println("str1 is" + str1);
		System.out.println("str2 is" + str2);

	}

	public static String nonStart(String a, String b) {
		if (a.length() == 1 && b.length() > 1) {

		 return b.substring(1,b.length());
		}
		
		else if (a.length() > 1 && b.length() == 1) {
		 return a.substring(1,a.length());
		} 
		
		else if (a.length() > 1 && b.length() > 1) {
		 return a.substring(1,a.length()) + b.substring(1,b.length());
		}
		
		return null;
		}
	
}
}

Open in new window


when i changed i got output
str1 isc
str2 isc

Seems now program is happy
0
gudii9Author Commented:
public String nonStart(String a, String b) {
		if (a.length() == 1 && b.length() > 1) {

		 return b.substring(1,b.length());
		}
		
		else if (a.length() > 1 && b.length() == 1) {
		 return a.substring(1,a.length());
		} 
		
		else if (a.length() > 1 && b.length() > 1) {
		 return a.substring(1,a.length()) + b.substring(1,b.length());
		}
		
		return null;
		
	

}

Open in new window


still i am failing one
Expected	Run		
nonStart("Hello", "There") → "ellohere"	"ellohere"	OK	    
nonStart("java", "code") → "avaode"	"avaode"	OK	    
nonStart("shotl", "java") → "hotlava"	"hotlava"	OK	    
nonStart("ab", "xy") → "by"	"by"	OK	    
nonStart("ab", "x") → "b"	"b"	OK	    
nonStart("x", "ac") → "c"	"c"	OK	    
nonStart("a", "x") → ""	"null"	X	    
nonStart("kit", "kat") → "itat"	"itat"	OK	    
nonStart("mart", "dart") → "artart"	"artart"	OK	    
other tests
OK	   

Open in new window


please advise
0
ozoCommented:
You are returning "null" when you want to return ""
0
ozoCommented:
And you have  4 separate cases where you only need 1
0
gudii9Author Commented:
public String nonStart(String a, String b) {
		
		 return a.substring(1) + b.substring(1);
		
		
	

}

Open in new window


above one works with one line

public String nonStart(String a, String b) {
		if (a.length() == 1 && b.length() > 1) {

		 return b.substring(1,b.length());
		}
		
		else if (a.length() > 1 && b.length() == 1) {
		 return a.substring(1,a.length());
		} 
		
		else if (a.length() > 1 && b.length() > 1) {
		 return a.substring(1,a.length()) + b.substring(1,b.length());
		}
		
		return "";
		
	

}

Open in new window


above code passed all tests
0
gudii9Author Commented:
public String nonStart(String a, String b) {
		if (a.length() == 1 && b.length() > 1) {

		 return b.substring(1,b.length());
		}
		
		else if (a.length() > 1 && b.length() == 1) {
		 return a.substring(1,a.length());
		} 
		
		else if (a.length() > 1 && b.length() > 1) {
		 return a.substring(1,a.length()) + b.substring(1,b.length());
		}
		

                if (a.length() == 1 && b.length()== 1) {
		return "";
		}

	return null;

}

Open in new window

above also passed all test cases
0
gudii9Author Commented:
They don't look the same to java
nonStart("x", "ac") → "c"      ""      X      
nonStart("x", "ac") → "c"      "c"      OK

Open in new window


i did not get above point.

when i ran my java program as below by passing above two arguments in both lines,
 i get same output as below


str1 is-->c
str2 is-->c


Can you please advise on what you mean by
They don't look the same to java
0
ozoCommented:
My comment in http:#a40441686 was in response to the "No. Both looks same to me" in http:#a40441458
because the code in http:#a40441216 results in
  nonStart("x", "ac") → "c"      ""      X  
when tested, but changing  the
  return "";
in line 11 to
  result= "";
would result in
  nonStart("x", "ac") → "c"      "c"      OK
like the code in http:#a40440736

Thus the difference between  return ""; and result = "";
causes the difference between
nonStart("x", "ac") → "c"      ""      X  
and    
nonStart("x", "ac") → "c"      "c"      OK
0
gudii9Author Commented:
Thus the difference between  return ""; and result = "";
so one is result other is return which is being assigned to "" which are completely two different things.
I thought difference is with some space or with double quote etc
0
gudii9Author Commented:
public String nonStart(String a, String b) {
  String result=null;
  String aFirst=null;
  String bFirst=null;
  
  if(a.length()>1) {
  result=a.substring(1,a.length());
  }
  else{
  
  return "";
  }
  if(b.length()>1) {
  result+=b.substring(1,b.length());
  }
 
  return result;
}

Open in new window



above is wrong and  below is correct

public String nonStart(String a, String b) {
  String result=null;
  String aFirst=null;
  String bFirst=null;
  
  if(a.length()>1) {
    result=a.substring(1,a.length());
  } else {
    result = "";
  }
  
  if(b.length()>1) result+=b.substring(1,b.length());

  
  return result;

}

Open in new window

0
gudii9Author Commented:
i see mistake clear and loud now.
Since i am returning result from my method in the else i should assign result ="" not return ""
0
ozoCommented:
More to the point, since result may yet need to be modified in line 12, you don't want to return before that has a chance to happen.
0
gudii9Author Commented:
More to the point, since result may yet need to be modified in line 12, you don't want to return before that has a chance to happen.
if a length is 1 then i have to return "" right before even reaching line 12

public String nonStart(String a, String b) {
  String result=null;
  String aFirst=null;
  String bFirst=null;
 
  if(a.length()>1) {
    result=a.substring(1,a.length());
  } else {
    result = "";
  }
 
  if(b.length()>1)
  {
  result+=b.substring(1,b.length());

  }
  else {
    result = "";
  }
  return result;

}



when i modified code one test case failed

Expected	Run		
nonStart("Hello", "There") → "ellohere"	"ellohere"	OK	    
nonStart("java", "code") → "avaode"	"avaode"	OK	    
nonStart("shotl", "java") → "hotlava"	"hotlava"	OK	    
nonStart("ab", "xy") → "by"	"by"	OK	    
nonStart("ab", "x") → "b"	""	X	    
nonStart("x", "ac") → "c"	"c"	OK	    
nonStart("a", "x") → ""	""	OK	    
nonStart("kit", "kat") → "itat"	"itat"	OK	    
nonStart("mart", "dart") → "artart"	"artart"	OK	    
other tests
X	    

Open in new window


i wonder why.(all i did was put else loop for b also)
when i say >= all are passing.
  if(b.length()>=1)
  {
  result+=b.substring(1,b.length());

But i never put in a condition check like that.
0
ozoCommented:
if a length is 1 then i have to return ""
not if b.length()>1

else for b
can destroy the result that you got from a
0
awking00Commented:
Why not forget about "result"? You have variables aFirst and bFirst declared, use them to evaluate your strings a and b seperately since that's what you're doing anyway.
if(a.length()>1) {
aFirst=a.substring(1);  ==> Note - the substring method only needs a begin index to get the rest of the string
  } else {aFirst = "";}
if(b.length()>1) {
bFirst=b.substring(1);
  } else {bFirst = "";}
return aFirst + bFirst;
}

So what this says in layman's terms is if str a is 1 character make the first part an empty string otherwise make if the substring of a starting at the second character, then it does the same thing for str b and returns their concatenation.
0
gudii9Author Commented:
public String nonStart(String a, String b) {
  
  String aFirst="";
  String bFirst="";
  
  if(a.length()>1) {
    aFirst=a.substring(1,a.length());
  } else {
    aFirst= "";
  }
  
  if(b.length()>1){ 
  bFirst=b.substring(1,b.length());}
  else {
    bFirst= "";
  }

  
  return aFirst+bFirst;

}

Open in new window


I wrote as above. I passed all tests. So this updated code looks good right?

i see first if else to check aString is greater than 1 or not.  (if yes do substring on it and assign to it if no assign to ""..but i already have to assign to "" at the top)

second if else to check aString is greater than 1 or not. (if yes do substring on it and assign to it if no assign to ""..but i already have to assign to "" at the top)

Do you suggest instead as below

public String nonStart(String a, String b) {
  
  String bFirst="";
  String bFirst="";
  
  if(a.length()>1) {
    aFirst=a.substring(1,a.length());
  } else {
    aFirst=aFirst ;
  }
  
  if(b.length()>1){ 
  bFirst=b.substring(1,b.length());}
  else {
    bFirst= bFirst;
  }

  
  return aFirst+bFirst;

}

Open in new window


but above code giving error as

Compile problems:


Error:      String bFirst="";
             ^^^^^^
Duplicate local variable bFirst


see Example Code to help with compile problems

please advise
0
ozoCommented:
On the former example, I might test >=1 instead of >1,
which would then become unnecessary since the challenge stipulates that "The strings will be at least length 1."

On the latter example, I might change one of
  String bFirst="";
  String bFirst="";
to aFirst

I might also eliminate the noop of
   bFirst= bFirst;
0
awking00Commented:
>>Error:      String bFirst="";
             ^^^^^^
Duplicate local variable bFirst<<

This is because of what I've been telling you about String objects being immutable. Once you have assigned bFirst the value of an empty string (""), it can not be changed (the same for aFirst), so you can not later modfify it to b.substring(1). You need to initialize the variables aFirst and bFirst to null and not to "".
0
ozoCommented:
You need to initialize the variables aFirst and bFirst to null and not to "".
In the context of this challenge, that is untrue.
0
gudii9Author Commented:
public String nonStart(String a, String b) {
  
  String aFirst="";
  String bFirst="";
  
  if(a.length()>1) {
    aFirst=a.substring(1,a.length());
  } else {
    aFirst="" ;
  }
  
  if(b.length()>1){ 
  bFirst=b.substring(1,b.length());}
  else {
    bFirst= "";
  }

  
  return aFirst+bFirst;

}

Open in new window


i initialized aFirst and bFirst both to "" and all test cases passed.

public String nonStart(String a, String b) {
  
  String aFirst=null;
  String bFirst=null;
  
  if(a.length()>1) {
    aFirst=a.substring(1,a.length());
  } else {
    aFirst="" ;
  }
  
  if(b.length()>1){ 
  bFirst=b.substring(1,b.length());}
  else {
    bFirst= "";
  }

  
  return aFirst+bFirst;

}

Open in new window


I also tried initializing aFirst and bFirst to null as above. Even then all then all test cases passed. Which approach is preferred.
0
ozoCommented:
Between those two choices, I think I'd prefer the one that would have worked even if it had been used with the code in http:#a40469798
0
gudii9Author Commented:
so initializing as below is better
 String aFirst="";
  String bFirst="";

Open in new window

 

compared to initializing as below right

 String aFirst=null;
  String bFirst=null;

Open in new window


Please advise
0
ozoCommented:
Initializing String aFirst=""; would make aFirst="" ; in line 9 unnecessary.

On the other hand, imposing extra conditions on your code can be a way of checking for errors.
0
gudii9Author Commented:
Initializing String aFirst=""; would make aFirst="" ; in line 9 unnecessary

so i should write as below? But it seems not working as below

public String nonStart(String a, String b) {
  
  String aFirst="";
  String bFirst="";
  
  if(a.length()>1) {
    aFirst=a.substring(1,a.length());
  } else {
    aFirst ;
  }
  
  if(b.length()>1){ 
  bFirst=b.substring(1,b.length());}
  else {
    bFirst;
  }

  
  return aFirst+bFirst;

}

Open in new window

0
awking00Commented:
Since you already set the values of aFirst and bFirst to "", the only time you want something different is when the length is > 1, so you don't need the else statements.
String aFirst="";
String bFirst="";
 
  if(a.length()>1) {
    aFirst=a.substring(1,a.length());
  }
  if(b.length()>1){
  bFirst=b.substring(1,b.length());
}
 
  return aFirst+bFirst;
}
0
gudii9Author Commented:
Since you already set the values of aFirst and bFirst to "",

 return aFirst+bFirst;

i thought it should add "" and "" and give "  "(one space and other space should add up two spaces right.

I see output as empty string only
nonStart("a", "x") → ""	""	OK	   

Open in new window


please advise
0
ozoCommented:
" " is one space
" " + " " -> "  "  (1+1=2 spaces)

"" is empty, with no space
"" + "" -> ""  (0+0=0 spaces)
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.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.