简体   繁体   中英

Java - How to use Dollar Sign

In one of my codes, I want the customer to be able to input the amount of money that they want to put into a machine, and the machine calculates how much change to give back to the customer. However, i want to make it so that if the customer DOES NOT enter a '$' before the amount of money they are paying, the system tells them to try again. Im not sure how to do this. This is my code so far

double customerPayment;
System.out.print("$ " + purchasePrice + " remains to be paid. Enter coin or note: ");
customerPayment = nextDouble();
//i want to tell the customer if they DONT input a '$' that they must try again

There are many ways to achieve that with a String . My advice: don't try to read a $ from a double.

You can do it like this:

double readCustomerPayment() {
    Scanner scanner = new Scanner(System.in);
    String inputStr = scanner.nextLine();
    scanner.close();

    if (!inputStr.startsWith("$")) {
        return readCustomerPayment();
    }

    String doubleStr = inputStr.substring(1);
    return Double.parseDouble(doubleStr);
}

You'd have to use a String type for scanning the input.

If the scanned input String is enteredString , the following code snippet would parse the string and provide a Double value.

if(enteredString.startsWith("$")){
        Double customerPayment = Double.parseDouble(enteredString.substring(1));
    }

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