syntax syntax - 1 month ago 11
Java Question

Surrounding a string with smileys

I've surrounded the string with smiley's but it's printing too many and everything I try doesn't seem to work.

My problem:

:):):):):):):):):):):):)
:) Surroundthis :)
:):):):):):):):):):):):)


My code:

private static void printWithSmileys(String characterString) {
loop(characterString);
if (characterString.length() % 2 == 0) {
System.out.println(":) " + characterString + " :)");
} else {
System.out.println(":) " + characterString + " :)"); // If string is an odd number, add a space
}
loop(characterString);
}

public static void loop(String characterString) {
String smile = ":)";
int length = characterString.length(); // Can test different lengths
for (int i = 0; i < length; i++) {
System.out.print(smile);
}
System.out.println();
}


Note: If the string is small enough, it will work but only for smaller strings

:):):):):):)
:) Method :)
:):):):):):)

Answer

You print out X smileys where X is the length of the string. Instead you should print the length of the string / 2 (since a smiley is 2 characters) + 2 more for the corners.

For method it accidentally works, because 6 smileys are 12 characters, and the word method is 6 characters and becomes 12 too when prefixed and postfixed with a smiley and a space.

This line should fix the issue:

int length = Math.ceil(characterString.length() / 2) + 3;

The 3 is for the two smileys on the corner and one extra to cover the spaces.

Comments