Visit the raindrops exercise on Exercism to read the full instructions and download the exercise files.
Dig Deeper
if statements
if statements
class RaindropConverter {
String convert(int number) {
StringBuilder stringBuilder = new StringBuilder();
if (number % 3 == 0) {
stringBuilder.append("Pling");
}
if (number % 5 == 0) {
stringBuilder.append("Plang");
}
if (number % 7 == 0) {
stringBuilder.append("Plong");
}
return stringBuilder.length() != 0 ? stringBuilder.toString() : Integer.toString(number);
}
}
This approach starts be defining a StringBuilder to build the result String.
A series of if statements uses the remainder operator to check if the number is evenly divisible
by 3, 5 or 7.
If so, the corresponding drop String is appended by the StringBuilder.
After the if statements, a ternary operator is used to check the StringBuilder.length().
If it is not 0, then the StringBuilder.toString() method is called and its value is returned.
If the length is 0, then the number is converted to a string using Integer.toString() and is returned.
The use of StringBuilder may not be as performant for so few appends, due to the time it takes to instantiate the StringBuilder.
Other ways of building the result may be faster.
Map
Map
import java.util.Map;
import java.util.TreeMap;
class RaindropConverter {
private static final TreeMap < Integer, String > lookup = new TreeMap < Integer, String > (
Map.of(3, "Pling", 5, "Plang", 7, "Plong"));
String convert(int number) {
var output = new StringBuilder("");
lookup.forEach((divisor, drop) -> {
if (number % divisor == 0)
output.append(drop);
});
return output.length() != 0 ? output.toString() : Integer.toString(number);
}
}
This approach begins by importing Map and TreeMap.
A private static final TreeMap is defined for efficient sorting of keys.
It is private because it doesn’t need to be seen outside the class.
It is static because it doesn’t need to differ between object instantiations, so it can belong to the class itself.
It is final because it does not need to be changed after it is created.
The Map.of() method is used to populate the map.
A StringBuilder is defined to build the result String.
The forEach() method is used to iterate the map entries.
The remainder operator is used to check if the number is evenly divisible
by the key of the map entry.
If so, the value of the map entry is appended by the StringBuilder.
After the forEach() is done, a ternary operator is used to check the StringBuilder.length().
If it is not 0, then the StringBuilder.toString() method is called and its value is returned.
If the length is 0, then the number is converted to a string using Integer.toString() and is returned.
The use of StringBuilder may not be as performant for so few appends, due to the time it takes to instantiate the StringBuilder.
Other ways of building the result may be faster.
Lihat Solusi Komunitas
The following are the top 3 community solutions by stars:
Source: Exercism java/raindrops