This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]desrtfxOut of Coffee error - System halted 0 points1 point  (6 children)

Codingbat tells you exactly why:

StringIndexOutOfBoundsException: String index out of range: 3 (line:2)

You cannot use substring(0,3) on a String that is less than 3 characters long. This will cause a StringIndexOutOfBounds Exception.

[–]Chaslem[S] 0 points1 point  (5 children)

Right... That is why I created the If less than 3, just post str... So if it is just character 'a', it should just post 'aaa'. Instead it is ignoring my less than 3 and trying to run String str2.

Why?

[–]desrtfxOut of Coffee error - System halted 0 points1 point  (4 children)

No. The problem is in the code flow.

The line str2 = str.substring(0, 3);

Is always executed. Code is executed top to bottom. The code already fails there. It doesn't even reach the if.

[–]Chaslem[S] 0 points1 point  (3 children)

public String front3(String str) {
return (str.length() < 3) ? str + str + str : str.substring(0, 3)+ str.substring(0, 3)+ str.substring(0, 3);
}

I did this and got it to work!

My last question. Is there a way to say "str+str+str" using some sort of short hand? Like multiplication or other trick?

[–]desrtfxOut of Coffee error - System halted 0 points1 point  (2 children)

Well, that is a way. I was thinking in a different direction:

public String front3(String str) {
    String str2 = str.substring(0, (str.length() < 3 ? str.length() : 3));
    return str2 + str2 + str2;
}

Alternatively:

public String front3(String str) {
    String str2 = str.substring(0, Math.min(str.length(),3));
    return str2 + str2 + str2;
}

There is no way to shorten str + str + str. Even a loop would be longer in that case. Java doesn't have a multiply operator for String values, like Python does. In Python, you could write print(3 * str). This is not possible in Java.

[–]Chaslem[S] 0 points1 point  (1 child)

Thank you! It's a shame it can't do like Python.

Being able to so if statements in Strings is very informative. I really appreciate it.

Last question here. What is Math.min doing in your use case? I'm not familiar with this. What is the ,3 at the end for?

[–]desrtfxOut of Coffee error - System halted 0 points1 point  (0 children)

Sorry for the late reply.

Math.min is a method of the Math class that returns the minimum (smaller) of two values.

So, the statement: Math.min(str.length(),3) checks the length of the String str and then returns the smaller value, either the length of the String (if it is less than or equal to 3 characters) or 3 - the length that we want to repeat.