Solved

last two characters of string challenge

Posted on 2014-11-14
23
238 Views
Last Modified: 2014-11-19
Hi,

I am working on below coding challenge
http://codingbat.com/prob/p103895
i wrote as below
public boolean endsLy(String str) {

int len=str.length();

if(str.substring(len-2).equals("ly")&& len>=2)
{
return true;
}
  return false;
}

Open in new window


My test cases are failing as below

Expected	Run		
endsLy("oddly") → true	true	OK	    
endsLy("y") → false	Exception:java.lang.StringIndexOutOfBoundsException: String index out of range: -1 (line number:5)	X	    
endsLy("oddy") → false	false	OK	    
endsLy("oddl") → false	false	OK	    
endsLy("olydd") → false	false	OK	    
endsLy("ly") → true	true	OK	    
endsLy("") → false	Exception:java.lang.StringIndexOutOfBoundsException: String index out of range: -2 (line number:5)	X	    
endsLy("falsey") → false	false	OK	    
endsLy("evenly") → true	true	OK	    
other tests

Open in new window

i would like to know how can improve on my above code.

i wonder why i keep getting string index out of bound many times.
Please advise.Thanks in advance
0
Comment
Question by:gudii9
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 9
  • 7
  • 7
23 Comments
 
LVL 84

Expert Comment

by:ozo
ID: 40443598
Do the  len>=2 on the left side of the && so it can prevent the substring(len-2) when it is false
0
 
LVL 7

Author Comment

by:gudii9
ID: 40443639
public boolean endsLy(String str) {

int len=str.length();

if(len>=2 && str.substring(len-2).equals("ly"))
{
return true;
}
  return false;
}

Open in new window


now it passed all as below
Expected	Run		
endsLy("oddly") → true	true	OK	    
endsLy("y") → false	false	OK	    
endsLy("oddy") → false	false	OK	    
endsLy("oddl") → false	false	OK	    
endsLy("olydd") → false	false	OK	    
endsLy("ly") → true	true	OK	    
endsLy("") → false	false	OK	    
endsLy("falsey") → false	false	OK	    
endsLy("evenly") → true	true	OK	    
other tests
OK

Open in new window


i did not realize first come first serve(i was under impression as long as both conditions there that is sufficient but in this case order also important)
0
 
LVL 84

Expert Comment

by:ozo
ID: 40443655
The && and || operators perform Conditional-AND and Conditional-OR operations on two boolean expressions. These operators exhibit "short-circuiting" behavior, which means that the second operand is evaluated only if needed.
https://docs.oracle.com/javase/tutorial/java/nutsandbolts/op2.html
In this case, it also means that the second operand is evaluated only if valid.
0
PeopleSoft Has Never Been Easier

PeopleSoft Adoption Made Smooth & Simple!

On-The-Job Training Is made Intuitive & Easy With WalkMe's On-Screen Guidance Tool.  Claim Your Free WalkMe Account Now

 
LVL 7

Author Comment

by:gudii9
ID: 40443676
if(len>=2 && str.substring(len-2).equals("ly"))

instead of above shortcircuit And if i use simle & as below
if(len>=2 & str.substring(len-2).equals("ly"))
i would have avoided this bottle neck. please advise
0
 
LVL 84

Expert Comment

by:ozo
ID: 40443711
No, & does not shortcut.  && is the shortcut operator
0
 
LVL 7

Author Comment

by:gudii9
ID: 40444050
public boolean endsLy(String str) {

int len=str.length();

if(str.substring(len-2).equals("ly")& len>=2 )
{
return true;
}
  return false;
}

Correct. When write like above i am getting string index out of bound

Expected	Run		
endsLy("oddly") → true	true	OK	    
endsLy("y") → false	Exception:java.lang.StringIndexOutOfBoundsException: String index out of range: -1 (line number:5)	X	    
endsLy("oddy") → false	false	OK	    
endsLy("oddl") → false	false	OK	    
endsLy("olydd") → false	false	OK	    
endsLy("ly") → true	true	OK	    
endsLy("") → false	Exception:java.lang.StringIndexOutOfBoundsException: String index out of range: -2 (line number:5)	X	    
endsLy("falsey") → false	false	OK	    
endsLy("evenly") → true	true	OK	    
other tests
OK	

Open in new window

0
 
LVL 32

Expert Comment

by:awking00
ID: 40444469
Think of what you are asking. If the substring beginning at the index of len - 2 equals "ly" then ...
If the length of the string is 0 or 1, then it's trying to evaluate the substring beginning at index -1 or -2, which will always be out of bounds.
0
 
LVL 84

Expert Comment

by:ozo
ID: 40445331
unlike with len>=2 && str.substring(len-2).equals("ly")
when you do str.substring(len-2).equals("ly")& len>=2, the str.substring(len-2) is executed regardless of whether the len>=2 is satisfied
0
 
LVL 32

Expert Comment

by:awking00
ID: 40449883
Another chance to use StringBuilder -
      public static boolean endsLy(String str) {
            StringBuilder sb = new StringBuilder(str);
            return sb.reverse().substring(0, 2).equalsIgnoreCase("yl");
      }
0
 
LVL 84

Expert Comment

by:ozo
ID: 40450005
    public static boolean endsLy(String str) {
            StringBuilder sb = new StringBuilder(str);
            return sb.reverse().substring(0, 2).equalsIgnoreCase("yl");
      }
Expected      Run      
endsLy("y") → false      Exception:java.lang.StringIndexOutOfBoundsException: String index out of range: 2 (line number:3)      X
endsLy("") → false      Exception:java.lang.StringIndexOutOfBoundsException: String index out of range: 2 (line number:3)      X

but
  return sb.reverse().toString().startsWith("yl");
would work
0
 
LVL 32

Expert Comment

by:awking00
ID: 40450111
Good point, ozo. I didn't test with 1 character or empty string. :-(
One more refinement would be using toLowerCase to make case insensitive.
return sb.reverse().toString().toLowerCase().startsWith("yl");
0
 
LVL 7

Author Comment

by:gudii9
ID: 40450119
public boolean endsLy(String str) {

int len=str.length();

if(len>=2 &str.substring(len-2).equals("ly") )
{
return true;
}
  return false;
}

Open in new window


without shortcut && if i use only one & and wrote as above still getting string out of bound which does not make sense to me.
for endsLy("y") it should not even go and check second condition in if loop right to throw exception?
  please advise
ndsLy("oddly") → true	true	OK	    
endsLy("y") → false	Exception:java.lang.StringIndexOutOfBoundsException: String index out of range: -1 (line number:5)	X	    
endsLy("oddy") → false	false	OK	    
endsLy("oddl") → false	false	OK	    
endsLy("olydd") → false	false	OK	    
endsLy("ly") → true	true	OK	    
endsLy("") → false	Exception:java.lang.StringIndexOutOfBoundsException: String index out of range: -2 (line number:5)	X	    
endsLy("falsey") → false	false	OK	    
endsLy("evenly") → true	true	OK	    
other tests

Open in new window

I like stringbuilder solution too.
0
 
LVL 84

Expert Comment

by:ozo
ID: 40450124
http://codingbat.com/prob/p103895 does not call for case insensitivity
0
 
LVL 84

Expert Comment

by:ozo
ID: 40450125
& does not shortcut.  && is the shortcut operator

& tries to evaluate both operands regardless of the value of the other operand.
0
 
LVL 7

Author Comment

by:gudii9
ID: 40450229
i see now why we only have to use &&

does not call for case insensitivity

what you mean by above statement. you mean like upper and and lower character does not matter for the challenge right?
0
 
LVL 32

Expert Comment

by:awking00
ID: 40450254
The CodingBat site says Given a string, return true if it ends in "ly", which is lower case and doesn't mention if it ends in "LY", so "LOVELY" would return false. I was interpreting the question (likely incorrectly) to return true if it ended in "LY", "Ly', "lY", or "ly".
0
 
LVL 84

Assisted Solution

by:ozo
ozo earned 250 total points
ID: 40450258
http://codingbat.com/prob/p103895 does say that upper and and lower character does not matter
so the toLowerCase() suggested in http:#a40450111 is uncalled-for

On the other hand, the problem does not clearly specify or test the behaviour for strings ending in "LY", so we cannot say that toLowerCase() is wrong.
Then again, while it doesn't explicitly specify the the case of "ly" must be exact, neither does it explicitly specify that the order of "ly" must be exact, nor does it test any cases that end in "yl" so it might also be argued that sorting before testing could also be valid.
0
 
LVL 7

Author Comment

by:gudii9
ID: 40450466
   public  boolean endsLy(String str) {
            StringBuilder sb = new StringBuilder(str);
           // return sb.reverse().substring(0, 2).equalsIgnoreCase("yl");
           return sb.reverse().toString().startsWith("ly");
      }

Open in new window

when i wrote as above it failed
Expected	Run		
endsLy("oddly") → true	false	X	    
endsLy("y") → false	false	OK	    
endsLy("oddy") → false	false	OK	    
endsLy("oddl") → false	false	OK	    
endsLy("olydd") → false	false	OK	    
endsLy("ly") → true	false	X	    
endsLy("") → false	false	OK	    
endsLy("falsey") → false	false	OK	    
endsLy("evenly") → true	false	X	    
other tests
X	  

Open in new window


nor does it test any cases that end in "yl" so it might also be argued that sorting before testing could also be valid.
i think it is failing if sorting or ordering(what is the difference?") is changing as above.
0
 
LVL 32

Expert Comment

by:awking00
ID: 40450500
It needs to be startsWith("yl") as you have reversed the string.
0
 
LVL 7

Author Comment

by:gudii9
ID: 40450558
Then again, while it doesn't explicitly specify the the case of "ly" must be exact, neither does it explicitly specify that the order of "ly" must be exact, nor does it test any cases that end in "yl" so it might also be argued that sorting before testing could also be valid.

i have not clearly understood above statement. Can you please elaborate.
0
 
LVL 32

Accepted Solution

by:
awking00 earned 250 total points
ID: 40450610
Why did we make it complicated? How about -
return sb.toString().endsWith("ly");
0
 
LVL 84

Expert Comment

by:ozo
ID: 40451249
public boolean endsLy(String str) {
  return str.endsWith("ly");
}
0
 
LVL 32

Expert Comment

by:awking00
ID: 40452239
ozo,
That's even less complicated and the best solution yet.
0

Featured Post

Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Windows Script Host (WSH) has been part of Windows since Windows NT4. Windows Script Host provides architecture for building dynamic scripts that consist of a core object model, scripting hosts, and scripting engines. The key components of Window…
The purpose of this article is to demonstrate how we can use conditional statements using Python.
This tutorial covers a step-by-step guide to install VisualVM launcher in eclipse.
Viewers will learn how to properly install Eclipse with the necessary JDK, and will take a look at an introductory Java program. Download Eclipse installation zip file: Extract files from zip file: Download and install JDK 8: Open Eclipse and …

717 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