简体   繁体   中英

How to only allow user to use certain values and have to make them use a $ in their input for my program

//Payment Process    
        System.out.println("Order payment");               
        System.out.println("-------------");            
        System.out.println("");    
        System.out.printf("$%.2f remains to be paid. Enter coin or note: ", totalPrice);    
        double payment;    
        payment = scan.nextInt();    
        while (payment <= totalPrice) {    
            System.out.printf("$%.2f remains to be paid. Enter coin or note:", totalPrice - payment);    
            payment += scan.nextInt();    

So I'm creating a project for Uni where I ask a user to buy coffee from my program. This is a snippet of the code under the payment process section. The two main questions I have are:
1. How do I make it so that the program only works when the input that is put in starts with a $ (eg. 10 would be invalid but $10.00 is valid)
2. How do I make it so that the user can only input $100.00, $50.00, $20.00, $10.00, $5.00, $2.00, $1.00, $0.50, $0.20, $0.10 and $0.05.

I wrote a small program, first is a String, so it can check whether the text is start with $ . Since your program is using number, so the String will be converted to double by remove the $ after this.

 public static void main(String[] args) {
        // TODO code application logic here  
        Scanner input = new Scanner(System.in);

        final String payment = input.next();
        if(payment.startsWith("$") && payment.matches(".*\\.\\d\\d"))
        {
           double paymentConverted = Double.parseDouble(payment.substring(1));
           // write ur others logic here
        }
        else
        {
             System.out.println("Invalid text !");
        }  
    }

startWith() used to check the first value, matches(".*\\\\.\\\\d\\\\d") check if string ends with two digits after a dot.


Between, you have some error on your code

 double payment;    
 payment = scan.nextInt(); 

should be nextDouble() if not mistaken.

answer for question 1: this checks if your input starts with a Dollar-sign($), you could move the code to a function and check it that way

public static void main(String[] args) {
  Scanner sc = new Scanner(System.in);

  boolean isValid = false;
  String input;
  do {
    System.out.printf("input: ");
    input = sc.next();

    //check if the input is valid
    if((input != null) && (input.length() > 0)) {
      if('$' == input.charAt(0)) {

        isValid = true;
        break;
      }
    }

    System.err.printf("Your input was invalid! input:%s%n", input);
  } while(!isValid);

  sc.close();

  System.out.printf("Your input was correct! input:%s%n", input);
}

rather crude but simple answer for question 1 & 2:

make a Set which contains all valid inputs and check if the input is contained in that very Set.

public static void main(String[] args) {
  Set<String> validInputs = new HashSet<>();

  validInputs.addAll(Arrays.asList("$100.00", "$50.00", "$20.00", "$10.00", "$5.00", "$2.00", "$1.00", "$0.50", "$0.20", "$0.10", "$0.05"));

  Scanner sc = new Scanner(System.in);

  boolean isValid = false;
  String input;
  do {
    System.out.printf("input: ");
    input = sc.next();

    // check if the input is valid
    if(validInputs.contains(input)) {
      isValid = true;
      break;
    }

    System.err.printf("Your input was invalid! input:%s%n", input);
  } while(!isValid);

  sc.close();

  System.out.printf("Your input was correct! input:%s%n", input);
}
  1. Use nextLine() instead of nextInt() to read input, because the addition of $ makes the input a String.

  2. When you have a short list of pre-set values that are acceptable input, the simplest way to validate input is to read the line from the user and simply compare this to a list of acceptable values that you already know.

      // Create a list of allowed values List<String> allowedValues = new ArrayList<>(Arrays.asList("$100.00", "$50.00", "$20.00")); // read user input String input = scan.nextLine(); // use the built-in contains() function on the List object if (!allowedValues.contains(input)) { System.out.println("Your input is not valid."); } System.out.println("Your input is valid."); 

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