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,
J
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;
else
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 {
Integer.parseInt(numInput);
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;
}
}