In addition to @Francesco Pitzalis's answer...
String
concatenation
String result = new String();
This is never required as String
s are immutable in Java. If you find yourself using it to append String
values, then you should be using StringBuilder
(the faster, non-synchronized version of StringBuffer
, which is usually recommended unless you require the multi-threading safety of the latter):
StringBuilder result = new StringBuilder();
// ...
result.append(integer % 2); // add some spaces for readability
// ...
return result.reverse().toString();
try-with-resources
// don't forget to close the Scanner
inputScanner.close();
Since you are on Java 7 at least (from the use of String
in switch
), you should be using try-with-resources
to safely and efficiently manage the underlying I/O resource used by your Scanner
instance:
try (Scanner scanner = new Scanner(System.in)) {
// ...
}
Choices and enum
s
On a related note to your isDecimalOrBinary()
method (which @Francesco Pitzalis's answer made a very good point), the return type can also be modeled as an enum
should you still choose to keep it:
enum ValueType {
DECIMAL, BINARY;
public static ValueType parse(String value) {
// ...
}
}
This eliminates the possibility of typos in your expected String
return values, e.g. when you return "decimal"
but are wrongly checking for "Decimal"
from calling the method.
- 19.4k
- 3
- 37
- 93