我已经为我的班级完成了这个项目而没有使用扫描仪功能。但是,当我阅读和研究时,我读到了扫描仪,它似乎可以使编码更容易,更有效。但是,我无法弄清楚如何让它发挥作用,所以如果有人能够对此有所了解,那将是非常有必要的。
public class Palindrome {
//Controls program execution
public static void main(String[] args) {
// Use Main to call other methods to perform the functions of checking user input for palindrome
int testNum = retrieveInput(0);
boolean isPalindrome = palCheck(testNum);
display(testNum, isPalindrome);
}
//prompt and retrieve user input and check if
//entry is numeric and is 5 numbers long
public static int retrieveInput(int testNum) {
String userInput = JOptionPane.showInputDialog("Enter a 5-digit number");
int StringLength = userInput.length();
try {
testNum = Integer.parseInt(userInput);
}
catch(Exception ex)
{
JOptionPane.showMessageDialog(null, "Please enter only numbers.");
return retrieveInput(testNum);
}
if (StringLength == 5)
return testNum;
else
JOptionPane.showMessageDialog(null, "Please enter exactly 5 digits.");
return retrieveInput(testNum);
}
//check if number is palindrome or not
public static Boolean palCheck(int testNum) {
int isPalindrome = testNum;
int rev = 0;
while (isPalindrome != 0){
int remainder = isPalindrome % 10;
rev = rev * 10 + remainder;
isPalindrome = isPalindrome/10;
}
if (testNum==rev)
return true;
else
return false;
}
//display results to user
public static void display(int testNum, boolean palCheck){
JOptionPane.showMessageDialog(null, testNum + " is" + ( palCheck ? " " : "not ") + "a palindrome.");
}
}
这是我完成并上交的作业,以下是我使用扫描仪的麻烦
public class Palindrome {
/**
* @param args
*/
//Controls program execution
public static void main(String[] args) {
// Use Main to call other methods to perform the functions of checking user input for palindrome or not
String testNum = retrieveInput();
boolean isPalindrome = palCheck(testNum);
display(testNum, isPalindrome);
}
//prompt and retrieve user input and check if
//entry is numeric and is 5 numbers long
public static String retrieveInput() {
Scanner testNum = new Scanner(System.in);
JOptionPane.showInputDialog("Enter a 5-digit number");
try {
return testNum.next("\\d\\d\\d\\d\\d");
}
catch(Exception ex)
{
JOptionPane.showMessageDialog(null, "Please enter a 5-digit number!");
return retrieveInput();
}
}
//check if number is palindrome or not
public static Boolean palCheck(String testNum) {
StringBuilder sb = new StringBuilder(testNum).reverse();
return testNum.equals(sb.toString());
}
//display results to user
public static void display(String testNum, boolean isPalindrome) {
JOptionPane.showMessageDialog(null, testNum + " is" + (isPalindrome ? " " : " not ") + "a palindrome.");
}
}
我的主要问题在于retrieveInput(),因为我相信其余代码可以工作,但我甚至无法使retrieveInput正常运行(IE,不会列出我的错误信息,重新启动方法,甚至显示任何内容。