簡體   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