In java is the preferred way of curly brace placing on the same line like you can see in code snippets in Oracles Style Guide.
reverse_string
has a type embedded in its name which leads to a code smell.
The disadvantage is that if you want to change the type of the parameter you have to change the method name too.
Additional the invocation looks messy and redundant compared to a method name without the embedded type:
if (user_string.equals(reverse_string(user_string)))
compared to
if (user_string.equals(reverse(user_string)))
Code can be descriptive by choosing good variable names.
Scanner input = new Scanner(System.in);
String user_string = input.nextLine().toLowerCase().replace(" ", "");
I think input
fits better than user_string
to describe the input of a user:
Scanner scanner = new Scanner(System.in);
String input = scanner.nextLine().toLowerCase().replace(" ", "");
if (input.equals(reverse(input))) { /*...*/ }
if (user_string.equals(reverse_string(user_string)))
{
System.out.println("It is a palindrome.");
} else
{
System.out.println("It is not a palindrome.");
}
The two System.out.println
are a bit like a duplication. You could save the message you want to print in a variable and then print it once to the console:
String message;
if (user_string.equals(reverse_string(user_string))) {
message = "It is a palindrome.";
} else {
message = "It is not a palindrome.";
}
System.out.println(message);
Or even shorter with the ternary operator:
String message = user_string.equals(reverse_string(user_string)) ? "It is a palindrome." : "It is not a palindrome.";
System.out.println(message);
I know that this a small script but I would like to introduce to think in objects:
public class Main {
private static final WhiteSpaceFreeScanner scanner = new WhiteSpaceFreeScanner(new Scanner(System.in));
public static void main(String[] args) {
final Input input = scanner.nextLine();
String message = input.isPalindrome() ? "It is a palindrome." : "It is not a palindrome.";
System.out.println(message);
}
}
class WhiteSpaceFreeScanner {
private final Scanner scanner;
CustomScanner(Scanner scanner) {
this.scanner = scanner;
}
Input nextLine() {
String input = scanner.nextLine().toLowerCase().replace(" ", "");
return new Input(input);
}
}
class Input {
private final String value;
public Input(String value) {
this.value = value;
}
Input reversed() { /* ... */ }
boolean isPalindrome() {
return this.equals(reversed());
}
@Override
public boolean equals(Object o) { /* ... */ }
@Override
public int hashCode() { /* ... */ }
}
.reverse()
method so writing your own is unnecessary if you want simple (but inefficient) code \$\endgroup\$