【发布时间】:2019-03-02 20:09:26
【问题描述】:
我正在制作我的第一个 java 项目,检查用户输入的单词(没有数字或符号)是否是回文。我使用了此处概述的方法:https://stackoverflow.com/a/4139065/10421526 用于逻辑。该代码按请求工作,但我无法在输入无效后重新提示用户,因为它似乎“阻止”了我的代码接受有效输入的能力,打印了我的“重试”消息。我也尝试过 do while 版本,但最终出现格式错误。我认为我定义我的 stringOut 变量的方式给我带来了麻烦,但我不知道如何改变它而不像 eclipse 所说的那样重复。这是经过数十次尝试后我能得到的最接近的:
import java.util.Scanner;
public class PalindromTester {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner in = new Scanner(System.in);
System.out.println("Input word to test: ");
String stringIn = in.nextLine();
String stringOut = new StringBuilder(stringIn).reverse().toString();
while (!stringIn.matches("[a-zA-Z]+")) {
System.out.println("Invalid input, try again.");
in.next(); //stops infinite error loop
}
if ((stringIn.equalsIgnoreCase(stringOut))) {
System.out.println("Palindrome detected");
System.out.println("You entered: " + stringIn);
System.out.println("Your string reversed is: " + stringOut);
} else {
System.out.println("Not a palindrome");
}
}
}
【问题讨论】:
-
问题是你永远不会改变
stringIn的值。在您的循环中,您需要执行stringIn = in.next();
标签: java loops validation