我的程序要求用户输入一堆数字,并用逗号分隔每个数字,例如(1,2,3,-4,55.0,100)。唯一有效的符号是“0”-“9”、“-”、“.”和“,”。我不知道如何限制这些符号的输入。
import java.util.Scanner;
import java.util.StringTokenizer;
public class Lab9Question2 {
public static void main(String[] args) {
double total = 0.0;
boolean askMore = true;
Scanner Keyboard = new Scanner(System.in);
while (askMore) {
System.out.println("Enter a series of numbers separated only by
commas or type QUIT to exit:");
String input = Keyboard.nextLine();
String tokens[] = input.split(",");
for (String str : tokens)
{
total += Integer.parseInt(str);
}
System.out.println(total);
if (input.equalsIgnoreCase("QUIT")){
askMore = false;
}
}
Keyboard.close();
}
}
这是我到目前为止所拥有的,当有人输入不允许的内容时,它仍然不会显示无效输入。
boolean askMore = true;
boolean inputValid = true;
Scanner Keyboard = new Scanner(System.in);
while (askMore) {
total = 0.0;
System.out.println("Enter a series of numbers separated only by
commas or type QUIT to exit:");
String input = Keyboard.nextLine();
inputValid = input.matches("[0-9]+" + "," + ".");
if (inputValid = false){
System.out.println("Invalid input");
}
最佳答案
您可以想到两种方法:
您可以将
System.out.println("输入一系列仅由 逗号或输入 QUIT 退出:"); 循环中的字符串输入 = Keyboard.nextline()
。输入完成后,您可以使用 Regex 来验证输入是否有效。如果没有,请发送消息并让用户编辑输入。如果可以,请转到input.Split()
另一个选项是获取每次按键的输入并识别输入是否无效。然后,您可以将输入框边框突出显示为红色,或者以其他方式提醒用户其输入无效。
编辑:原始答案中缺少代码行,格式设置。
关于java - 我不知道如何将用户输入限制为数字和逗号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43164235/