繁体   English   中英

我无法弄清楚如何限制用户输入数字和逗号

[英]I can't figure out how to limit user input to numbers and commas

我的程序要求用户输入一串用逗号分隔每个数字的数字,如(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");
        }

您可以通过两种方式来实现这一点:

  1. 你可以把你的System.out.println("Enter a series of numbers separated only by commas or type QUIT to exit:"); String input = Keyboard.nextline() System.out.println("Enter a series of numbers separated only by commas or type QUIT to exit:"); String input = Keyboard.nextline()循环中的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. 另一种选择是获取每个键盘的输入并识别输入是否无效。 然后,您可以突出显示输入框边框红色或以其他方式提醒用户输入无效。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM