【问题标题】:I can't figure out how to limit user input to numbers and commas我不知道如何将用户输入限制为数字和逗号
【发布时间】: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


【解决方案1】:

我想到了两种方法:

  1. 您可以将System.out.println("Enter a series of numbers separated only by commas or type QUIT to exit:"); String input = Keyboard.nextline() 放入一个循环中。输入完成后,您可以使用 Regex 验证输入是否有效。如果没有,请发送消息并让用户编辑输入。如果没问题,请移至input.Split()

  2. 另一种选择是获取每个按键的输入并识别输入是否无效。然后,您可以将输入框边框突出显示为红色,或者以其他方式提醒用户他们的输入无效。

编辑:原始答案中缺少代码行,格式。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-10-18
    • 2019-04-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多