To answer your comment, yes there are equivalent of PEP8 in java. I suggest checkstyle, this plugin works in lots of IDE / text editors and can be configured with your code style.
Code review
reverse_string method
- In java, we try to use the upper-case version of
Snake caseonly on constants, for / enums. For the methods and variablevariables, I suggest that you use theCamel casestyle.
Before
private static String reverse_string(String my_string)
{
//[..]
}
After
private static String reverseString(String myString)
{
//[..]
}
- When concatenating
Stringin a loop, it's generally recommended to use ajava.lang.StringBuilderto gain performance and take fewer operations.
private static String reverseString(String myString)
{
StringBuilder reversedString = new StringBuilder();
for (int j = myString.length() - 1; j >= 0; j--)
{
reversedString.append(myString.charAt(j));
}
return reversedString.toString();
}
If you want not to use it, then I suggest the += operator instead of the +; it will give the same result and make the code shorter.
Other observations
The code was missing a bit of formatting, but nothing too important, I sugest that you pick a formatter for your style (Horstmann style) depending on your IDE / text editor.
Refactored code
private static String reverseString(String myString)
{
String reversed_stringreversedString = "";
for (int j = myString.length() - 1; j >= 0; j--)
{
reversed_stringreversedString += myString.charAt(j);
}
return reversed_string;reversedString;
}
public static void main(String[] args)
{
System.out.print("Insert a 'String': ");
Scanner input = new Scanner(System.in);
String userString = input.nextLine().toLowerCase().replace(" ", "");
if (userString.equals(reverseString(userString)))
{
System.out.println("It is a palindrome.");
}
else
{
System.out.println("It is not a palindrome.");
}
}