【发布时间】:2017-08-27 02:46:46
【问题描述】:
我的程序要求用户输入一堆数字,用逗号分隔每个数字,例如 (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");
}
【问题讨论】:
-
我不认为试图限制用户的输入是正确的方法。相反,您应该验证用户的输入
-
是的,对不起,这就是我的意思,这就是我目前所拥有的,但仍然没有输出“无效输入”。当有人输入超出可用范围的符号时。我把新代码贴在上面,不知道怎么放这里。
标签: java validation input user-input