Liam
Liam

Reputation: 77

Java: Loop issues

I'm writing a relatively simple Java program that calculates discounts for shoppers if they have certain vouchers or bonuses. It's working okay, but I have an issue when the program asks the user if they have any vouchers.

If they type "n", they still have to go through the loop as if they responded with "y" once before they can exit. I know it's probably a dumb mistake in there somewhere, but it's been driving me crazy and I'd appreciate a pair of fresh eyes to once it over.

do {
    System.out.println("Please enter the total price of the goods");
    price = keyboard.nextDouble();
    if (price < limits[0] || price > limits[1]) {
        System.out.println("Invalid price. Please try again");
        validPrice = false;
    } else {
        validPrice = true;
    }
} while (!validPrice);

keyboard.nextLine();

do {
    System.out.println("Does the customer have any additional discounts? y/n");
    choice = keyboard.nextLine();

    if (!choice.matches(inputRegexMatchPattern)) {
        System.out.println("Invalid input – please re-enter");
    } else if (choice.toLowerCase().charAt(0) == 'y') ;
    {
        System.out.println(choice);
        do {
            System.out.println("What type of discount does the customer have? [L]oyalty Card/[D]iscount Voucher");
            input = keyboard.nextLine();

            if (!input.matches(discountRegexMatchPattern)) {
                System.out.println("Invalid input – please re-enter");
            }
        } while (!input.matches(discountRegexMatchPattern));

        if (input.charAt(0) == 'l' || input.charAt(0) == 'L') {
            voucherDiscounts += voucherDiscountsArray[0];
            System.out.println("Loyalty Card discount accepted");
        } else if (input.charAt(0) == 'd' || input.charAt(0) == 'D') {
            voucherDiscounts += voucherDiscountsArray[1];
            System.out.println("Discount Voucher accepted");
        }
    }
} while (!(choice.toLowerCase().charAt(0) == 'n'));

Upvotes: 0

Views: 83

Answers (2)

Makoto
Makoto

Reputation: 106430

You have a semicolon here:

else if (choice.toLowerCase().charAt(0) == 'y') ;

What that means is your loop will continue to execute in spite of the selection you make. Java interprets this if statement as not having any body.

Remove the semicolon and you should be good to go.

Upvotes: 3

Samuel
Samuel

Reputation: 2156

The do while construct always performs the content of the loop BEFORE it actually tests the condition.

I guess what you want here is a simple while loop.

Upvotes: 0

Related Questions