【发布时间】:2019-12-09 05:01:34
【问题描述】:
我正在尝试允许仅使用字符 a-zA-Z 进行的输入并且还有空格。示例:“查克·诺里斯”。
以下代码发生的情况是扫描仪input.next() 不允许上述示例输入字符串。
我希望这个输出:Success! 但这是实际输出:Again:
try {
String input_nome = input.next(); // Source of the problem
if (input_nome.matches("[a-zA-Z ]+")) {
System.out.print("Success!");
break;
} else {
System.err.print("Again: ");
}
} catch (Exception e) {
e.printStackTrace();
}
解决方案
问题的根源在于使用的扫描仪方法。
String input_nome = input.next(); // Incorrect scanner method
String input_nome = input.nextLine(); // Correct scanner method
【问题讨论】:
-
如答案之一所述,您的代码工作正常,因此如果您得到错误的结果,问题与您的 reg exp 模式无关。
标签: java regex string input java.util.scanner