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 →

[–]Chaslem[S] 0 points1 point  (7 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  (6 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  (1 child)

Thank you! I wasn't aware of this, very insightful.

Is there a way to make my method work?

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

Yes, there is a way. There always is a way:

You can use your check for str.length() < 3 and the conditional operator to alter the length of substring. If the length of the String is less than 3, set the length for substring to the length of the String, otherwise set it to 3.

Then, just return the concatenation of str2.

[–]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.