Avatar of gudii9
gudii9
Flag for United States of America asked on

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
JavaProgramming Languages-OtherJava EE

Avatar of undefined
Last Comment
ozo

8/22/2022 - Mon
SOLUTION
Vsevolod Geraskin

Log in or sign up to see answer
Become an EE member today7-DAY FREE TRIAL
Members can start a 7-Day Free trial then enjoy unlimited access to the platform
Sign up - Free for 7 days
or
Learn why we charge membership fees
We get it - no one likes a content blocker. Take one extra minute and find out why we block content.
Not exactly the question you had in mind?
Sign up for an EE membership and get your own personalized solution. With an EE membership, you can ask unlimited troubleshooting, research, or opinion questions.
ask a question
SOLUTION
mccarl

Log in or sign up to see answer
Become an EE member today7-DAY FREE TRIAL
Members can start a 7-Day Free trial then enjoy unlimited access to the platform
Sign up - Free for 7 days
or
Learn why we charge membership fees
We get it - no one likes a content blocker. Take one extra minute and find out why we block content.
Not exactly the question you had in mind?
Sign up for an EE membership and get your own personalized solution. With an EE membership, you can ask unlimited troubleshooting, research, or opinion questions.
ask a question
ozo

What is the purpose of the test on line 5?
gudii9

ASKER
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

Vsevolod Geraskin

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

Experts Exchange has (a) saved my job multiple times, (b) saved me hours, days, and even weeks of work, and often (c) makes me look like a superhero! This place is MAGIC!
Walt Forbes
SOLUTION
Log in to continue reading
Log In
Sign up - Free for 7 days
Get an unlimited membership to EE for less than $4 a week.
Unlimited question asking, solutions, articles and more.
gudii9

ASKER
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

ozo

awking00: Did you actually try that?
ozo

gudii9: Do yo see the difference between  return ""; and result = "";?
Get an unlimited membership to EE for less than $4 a week.
Unlimited question asking, solutions, articles and more.
gudii9

ASKER
No. Both looks same to me
ozo

They don't look the same to java
nonStart("x", "ac") → "c"      ""      X      
nonStart("x", "ac") → "c"      "c"      OK
gudii9

ASKER
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
Experts Exchange is like having an extremely knowledgeable team sitting and waiting for your call. Couldn't do my job half as well as I do without it!
James Murphy
awking00

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;
}
gudii9

ASKER
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
ozo

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

Get an unlimited membership to EE for less than $4 a week.
Unlimited question asking, solutions, articles and more.
awking00

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;
            }
gudii9

ASKER
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
gudii9

ASKER
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
I started with Experts Exchange in 2004 and it's been a mainstay of my professional computing life since. It helped me launch a career as a programmer / Oracle data analyst
William Peck
ozo

You are returning "null" when you want to return ""
ozo

And you have  4 separate cases where you only need 1
gudii9

ASKER
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
Get an unlimited membership to EE for less than $4 a week.
Unlimited question asking, solutions, articles and more.
gudii9

ASKER
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
gudii9

ASKER
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
ozo

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
This is the best money I have ever spent. I cannot not tell you how many times these folks have saved my bacon. I learn so much from the contributors.
rwheeler23
gudii9

ASKER
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
gudii9

ASKER
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

gudii9

ASKER
i see mistake clear and loud now.
Since i am returning result from my method in the else i should assign result ="" not return ""
Get an unlimited membership to EE for less than $4 a week.
Unlimited question asking, solutions, articles and more.
ozo

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.
gudii9

ASKER
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.
ozo

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
All of life is about relationships, and EE has made a viirtual community a real community. It lifts everyone's boat
William Peck
awking00

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.
gudii9

ASKER
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
ozo

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;
Get an unlimited membership to EE for less than $4 a week.
Unlimited question asking, solutions, articles and more.
awking00

>>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 "".
ozo

You need to initialize the variables aFirst and bFirst to null and not to "".
In the context of this challenge, that is untrue.
gudii9

ASKER
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.
Your help has saved me hundreds of hours of internet surfing.
fblack61
ozo

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
gudii9

ASKER
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
ozo

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.
Get an unlimited membership to EE for less than $4 a week.
Unlimited question asking, solutions, articles and more.
gudii9

ASKER
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

awking00

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;
}
gudii9

ASKER
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
Experts Exchange has (a) saved my job multiple times, (b) saved me hours, days, and even weeks of work, and often (c) makes me look like a superhero! This place is MAGIC!
Walt Forbes
ASKER CERTIFIED SOLUTION
Log in to continue reading
Log In
Sign up - Free for 7 days
Get an unlimited membership to EE for less than $4 a week.
Unlimited question asking, solutions, articles and more.