简体   繁体   中英

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

my program asks the user to input a bunch of numbers with commas separating each number so like (1,2,3,-4,55.0,100). The only valid symbols being "0"-"9", "-", ".", and ",". I cant figure out how to limit the input to these symbols.

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();
}
}

This is what I have so far, it still wont display invalid input when someone enters something that is not allowed.

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");
        }

There are two ways you can do this that come to mind:

  1. You can put your 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() in a loop. When the input is finished being entered, you use Regex to validate if the input is valid. If not, message and have user edit the input. If okay, move to input.Split()

  2. Another option is to get the input on each keyup and recognize if the input is invalid. You can then highlight the input box border red or otherwise alert the user that their input is invalid.

Edit: Missed line of code in original answer, formatting.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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