我需要验证用户输入字符串以确保它包含逗号。 如果它不包含逗号,则必须打印"错误"并允许用户重新输入。 我只是不确定要使用哪个循环。 如果其他可能有效,但我需要它循环回扫描仪以供用户输入。还是使用 .contains 的 while 循环?谢谢。
如果你想
使用循环,我推荐for-each循环:
boolean found = false;
while (found == false) {
String input = "this is a sentence, with a comma"; // read input here
for (char ch: input.toCharArray()) {
if (ch == ',') {
found = true;
}
}
if (found == false) {
System.out.println("Error");
}
}
Java 中可能会有内置的函数,例如返回布尔值的"string.contains(character)"
input.contains(",")