I may actually have time to do some coding, now that I’m a Java Associate (see last post) and the intense studying has ended for a while. To kick things off I decided to go back to some of the early tutorials our class studied in the first month or so of the SCJA 6 course. At the time, the palindrome program we covered was pretty confusing, and I wanted to see how I’d fair trying this without revising my notes.

I produced the code below. There may be better ways of checking if a word is palindromic, but this one works just fine as far as I can see. I commented it throughout, so hopefully Java Noobs will follow easy enough. You can copy and paste and run it in your IDE. Test it with ABBA, ABBBA, AB BA, AB56BA etc.

Basically the code takes a word input by the user and makes a reversed copy of it. Then it checks to see if both words have the same content with the String .equals() method. If the word is the same in reverse then we have a palindrome. The rest of the code checks for empty spaces in the word, and checks to ensure only characters are input by the user.

I’m open to advice/critic so please feel free to comment below any suggestions you may have regarding the code!

package palindrome;
import java.util.Scanner;
/**
*
* @author
*/
public class Palindrome {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {

//Read in with Scanner
Scanner buffer = new Scanner(System.in);
System.out.println("Type a word here to be tested for palindrome: ");
String input = buffer.nextLine().toLowerCase().trim();

//Checking: if the input is not a character
if (!input.matches("[a-zA-Z]+") || input.contains(" ")){
System.out.println("Invalid input, you may have entered a number, "
+ "space or non-character. Start again!");
}
//create a new reverse string
String reverse = new StringBuffer(input).reverse().toString();
//compare the strings
if(input.length() > 0 && input.equals(reverse)){
System.out.println("The word you entered is a palindrome.");
}
//Checking: if they don't enter a string and just hit enter...
else if(input.isEmpty()){
System.out.println("You did not enter a word. Start again!");
}
//if the string is empty or is not palindromic...
else{
System.out.println("You did NOT submit a palindrome word.");
}
}
}