Firstly, this is something I see a distressing amount in beginner Java programmers:
removeSpace(word).compareTo(removeSpace(reversed)) == 0
There's a method for checking if two Strings are equal. It's called equals
. It'd be used like this:
removeSpace(word).equals(removeSpace(reversed))
If you wanna ignore case, you could use equalsIgnoreCase
:
removeSpace(word).equalsIgnoreCase(removeSpace(reversed))
Secondly, a formatting tip: Except in method declarations or calls, always put a space before (
and a space after )
. So, for example:
if(...) {
becomes
if (...) {
In your removeSpaces
method:
- In general, when find that you're doing it a lot, avoid using
String += String
. Instead, initialize a StringBuilder
and append
to it.
String#charAt()
returns a char
, which can be compared with ==
; I'm not sure why you first turn it into a String
, then use compareTo
(which, again, should be equals
, since you were comparing Strings for equality)
With those issues fixed, this is what the method looks like:
private static String removeSpace(String aword) {
StringBuilder buffer = new StringBuilder();
for (int i = 0; i < aword.length(); i++) {
if (aword.charAt(i) != ' ')) {
buffer.append(aword.charAt(i));
}
}
return buffer.toString();
}
(Note that I changed what would have been !(... == ...)
to ... != ...
and that ' '
uses single quotes.)
The whole function could be replaced with word.replaceAll(" ", "")
, but that's no fun, so I'm gonna keep using yours through here. Besides, it's a good way to practice to write your own methods -- just remember, when you're writing production code, to do a thorough search of the docs first. If there's a version in the standard API, a whole gaggle of people have been optimizing it to high heaven, and it might even be implemented in native code. That alone would make it a bazillion times faster than anything you could write in pure Java.
You use removeSpaces
in the comparison, which somewhat obfuscates what really happens: The String is checked for palindromity (word coined?) ignoring the spaces. It's clearer to move those method calls to when you get it (plus, this removes an extra function call, which is more efficient :D):
word = removeSpaces(in.nextLine());
// ...
if(word.equals(reversed)) { // Note that I'm not using compareTo here
// etc.
Thirdly, I'd recommend pulling the code that reverses your String into another method that takes a String argument and returns a String (and applying my earlier advice about StringBuilder
):
public static String reverse(String word) {
StringBuilder reversed = new StringBuilder(word.length);
for(int i = word.length(); i > 0; i--) {
reversed.append(word.charAt(i - 1));
}
}
In that snippet above, I also removed length
, since it's ultimately useless. You're only using it once, so there's no point in declaring a variable, and it's actually clearer to be able to directly see what String's length we're talking about -- you don't need to go back in the code to see what it means
With all this, your main
becomes a bit clearer:
public static void main(String args[]) {
String word = "";
String reversed = "";
Scanner in = new Scanner(System.in);
System.out.println("Please enter the string: ");
word = removeSpaces(in.nextLine());
reversed = reverse(word);
if (word.equals(reversed)) {
System.out.println("The string " + word + " is a palindrome");
}
else {
System.out.println("The string " + word + " is not a palindrome");
}
}
We could clean it up a little more by moving your word
and reversed
declarations to where the variables are first assigned, rather than their own lines (which, incidentally, don't need the = ""
because they aren't used before you assign them later):
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.println("Please enter the string: ");
String word = removeSpace(in.nextLine());
String reversed = reverse(word);
if (word.equals(reversed)) {
System.out.println("The string " + word + " is a palindrome");
}
else {
System.out.println("The string " + word + " is not a palindrome");
}
}
This means that your whole class, all together, looks something like this:
public class Reversal {
public static String reverse(String word) {
StringBuilder reversed = new StringBuilder(word.length);
for (int i = word.length(); i > 0; i--) {
reversed.append(word.charAt(i - 1));
}
}
private static String removeSpace(String aword) {
StringBuilder buffer = new StringBuilder();
for (int i = 0; i < aword.length(); i++) {
if(aword.charAt(i) != ' ')) {
buffer.append(aword.charAt(i));
}
}
return buffer.toString();
}
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.println("Please enter the string: ");
String word = removeSpace(in.nextLine());
String reversed = reverse(word);
if (word.equals(reversed)) {
System.out.println("The string " + word + " is a palindrome");
}
else {
System.out.println("The string " + word + " is not a palindrome");
}
}
}
If you want to get rid of your custom method to remove spaces (which I would recommend doing if you ever had to remove spaces in production code):
public class Reversal {
public static String reverse(String word) {
StringBuilder reversed = new StringBuilder(word.length);
for (int i = word.length(); i > 0; i--) {
reversed.append(word.charAt(i - 1));
}
}
private static String removeSpace(String aword) {
StringBuilder buffer = new StringBuilder();
for (int i = 0; i < aword.length(); i++) {
if(aword.charAt(i) != ' ')) {
buffer.append(aword.charAt(i));
}
}
return buffer.toString();
}
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.println("Please enter the string: ");
String word = in.nextLine().replaceAll(" ", "");
String reversed = reverse(word);
if (word.equals(reversed)) {
System.out.println("The string " + word + " is a palindrome");
}
else {
System.out.println("The string " + word + " is not a palindrome");
}
}
}
And, finally, an utterly unreadable version of your code that does the same thing, which you should never use but was annoyingly fun to write so I thought I'd provide it anyway:
public static void main(String args[]) {
String l;
System.out.println("The string "+(l=new Scanner(System.in).nextLine())+" is"+(l.replaceAll(" ", "").equals(new StringBuilder(l).reverse().toString().replaceAll(" ", ""))?" ":" not ")+"a palindrome");
}
word = word.replace(" ","").toUpperCase();
to remove spaces and make everything the same capitalization, and then for checking if a palindromefor(int i=0; i<word.length()/2;i++){ if(word.charAt(i)==word.charAt(word.length-1-i)){ return false; }} return true;
This will compare all the characters from the beginning with the end, up until the midpoint. If it doesn't return false by the end, then it is true! Hopefully this is helpful in more of a problem solving sense in the future. \$\endgroup\$