I'm new to Java (2 weeks) and was given a class assignment to create a program that takes a 5 digit number and checks to see if it is a palindrome (same forwards as backwards.) The requirement stated to use the methods main(), retrieveInput(), check(), and display().
My code works fine but it seems (is) clunky.
I'm basically looking for feedback as to best practice, ways to improve my code, things that someone more familiar with Java would have done differently. void methods, static (global?) variables, better error handling (as the error handling only works up to the point where you enter the second non-numeric value) I'm perfectly fine submitting my work as it is. I'm just trying to speed up my learning curve, so additional insight would be helpful.

Thanks in advance,


package pal;

import javax.swing.JOptionPane;

public class Palindrome {
	public static void main(String[] args) {
		int myNumber;	
		boolean test;
		myNumber = retreiveInput();
		test = check(myNumber);
		display(test, myNumber);

	private static void display(boolean myTest, int displayNumber) {
		if (myTest == true){
			JOptionPane.showMessageDialog(null, "The number " + displayNumber + " IS a palindrome!",
					 "Success!", JOptionPane.PLAIN_MESSAGE);	
		else {
			JOptionPane.showMessageDialog(null, "The number " + displayNumber + " IS NOT a palindrome!",
					 "Sorry!", JOptionPane.PLAIN_MESSAGE);	}

	private static boolean check(int newNumber) {
		int a;
		int b;
		int c;
		int d;
		int e;
		boolean isPalindrome = false;
		 a = newNumber / 10000;
		 b = newNumber % 10000;
		 b = b / 1000;
		 c = newNumber % 1000;
		 c = c / 100;
		 d = newNumber % 100;
		 d = d / 10;
		 e = newNumber % 10;
		 if (a == e && b == d)
			 isPalindrome = true;
			 isPalindrome = false;
		 return isPalindrome;	

	private static int retreiveInput() {
		String numInput;		
		numInput = JOptionPane.showInputDialog("Please enter a 5 digit number. \nLonger numbers will be truncated.");	
		boolean inputAccepted = false;	 
		 while(!inputAccepted) {
		   try {
		       inputAccepted = true;
		   catch(NumberFormatException e1) {
			   numInput = JOptionPane.showInputDialog("Please enter numbers only.");	
		if (numInput != null && numInput.length() > 5)
		    numInput = numInput.substring(0, 5);
		int number = Integer.parseInt(numInput);			 
		return number;

Member Avatar for hfx642

Well... I would have left everything as a String and not bother doing any conversion.

String s1 = "abcde";
String s2 = "";  // Holds the REVERSE of s1
for (int i = s1.length() - 1; i >= 0; i--) s2 = s2 + s1.substring (i, i+1);
if (!s2.equals(s1)) System.out.print("NOT a ");
System.out.println ("Palindrome");
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.