在Java中重复提示,直到字符串中的所有字符都可接受为止
我对java相当陌生,正在尝试制作一个罗马数字计算器。我已经完成了主编码,但我想添加检查主字符串中“非法”字符的功能 我创建了一个名为“ValidCheck”的方法,用于根据可接受字符列表测试字符串中的所有字符在Java中重复提示,直到字符串中的所有字符都可接受为止,java,string,loops,roman-numerals,Java,String,Loops,Roman Numerals,我对java相当陌生,正在尝试制作一个罗马数字计算器。我已经完成了主编码,但我想添加检查主字符串中“非法”字符的功能 我创建了一个名为“ValidCheck”的方法,用于根据可接受字符列表测试字符串中的所有字符 public static boolean ValidCheck(String letter){ boolean okay = true; for (int i = 0; i < Letters.length; i++){ if (Letters[i
public static boolean ValidCheck(String letter){
boolean okay = true;
for (int i = 0; i < Letters.length; i++){
if (Letters[i] != letter){
okay = false;
}
}
return okay;
}
前
我想知道如何将其放入循环中重复询问,直到使用该方法认为输入是可接受的?
另外,由于我是一个相当新的解释它是如何重复的,以及如何从循环返回值将非常感谢 我建议将
java.util.Scanner
与无止境循环结合使用。扫描仪
易于使用,可解决许多常见任务
示例代码可能如下所示:
import java.util.Scanner;
public class LoopingInput {
public static void main(String[] args) {
try (Scanner scanner = new Scanner(System.in)) {
for (;;) {
System.out.println("Type in a Roman Numeral value: ");
String nextLine = scanner.nextLine();
if (!nextLine.matches("[IVXLCDM]+")) {
System.out.println("Error with input. Unexpected character.");
}
// you may want to "return nextLine" or similar in an "else" branch
}
}
}
}
说明:
是Java-8的一个特性,它会自动关闭一个对象,即使发生意外情况try(…){…}
是默认输入,在大多数情况下是命令行或文件输入System.in
等待用户输入新行;并返回该行scanner.nextLine()
正在使用正则表达式验证输入。这在这种情况下非常方便。它搜索nextLine.matches(“[IVXLCDM]+”)
字符的任意数量(IVXLCDM
)+
如果(字母[i]!=letter){
->我认为应该在输入有效时返回。
Type in a Roman Numeral : MMDK
Error with input. Unexpected character.
Type in a Roman Numeral :
import java.util.Scanner;
public class LoopingInput {
public static void main(String[] args) {
try (Scanner scanner = new Scanner(System.in)) {
for (;;) {
System.out.println("Type in a Roman Numeral value: ");
String nextLine = scanner.nextLine();
if (!nextLine.matches("[IVXLCDM]+")) {
System.out.println("Error with input. Unexpected character.");
}
// you may want to "return nextLine" or similar in an "else" branch
}
}
}
}