-4

I have a problem with my restaurant assignment - I'm required to

  1. Create a while loop with a required quantity that user purchases to be between 1 and 15. User has 3 attempts and if after the third time he doesn't put the right quantity 1

  2. Using a do- while loop user has to answer if he wants to run a program again. If he answers 'Y' (for yes) it runs again, if the answer is 'N' (for no ) it terminates.

I keep getting errors: the while loop does only 2 attempts, and the do while doesn't work at all.

    import java.text.DecimalFormat;
    import java.util.Scanner;

    public class newone {
       public static void main (String[] args){
         char repeat;             
         // To hold 'y' or 'n'      
         String input;      

        DecimalFormat df = new DecimalFormat("$0.00");
        //to use: df.format(doubleVariable)

        //Display any welcome message at the top of the output screen
        System.out.println("Welcome!");

        double price = 5.0;
        System.out.println("Burger is " + df.format(price));

        Scanner keyboard = new Scanner(System.in); 

            int attempts = 0;
            int maxAttempts = 3;
            int quantity;

            System.out.print("Enter amount of burgers: ");

            quantity = keyboard.nextInt();
        //LESS THAN OR EQUAL TO 3... 
        while(quantity <1 || quantity >=15 && attempts<=maxAttempts){

            if(quantity < 1 || quantity >= 15){

                System.out.println("That is an invalid amount, please try  again");
                    quantity= keyboard.nextInt();
                    ++attempts;
                    }
                    else if(quantity>1 && quantity<15){

                //user entered a valid amount  
                System.out.println("The amount is valid. You ordered: "+ quantity);
                double subTotal = quantity * price;
            }

            while (attempts>=maxAttempts){
                System.out.println("Too many attempts, you can't order");
                break;
                }
            }

         do{ 
     System.out.println("Would you like to run the program again?");        
     System.out.print("Enter Y for yes or N for no: "); 
     input = keyboard.nextLine();    // Read a line.     
     repeat = input.charAt(0);       // Get the first char.   
     } 
//it gives me an error Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 0
    at java.lang.String.charAt(Unknown Source)

     while (repeat == 'Y' || repeat == 'y'); 



            }
        }}
Dany
  • 11
  • 6
  • Put `System.out.println("String length" + input.length());` after your `input = keyboard.nextLine();`. – PM 77-1 Mar 04 '16 at 21:46

2 Answers2

0

Below line causes the error:

repeat = input.charAt(0);

Perhaps user is not providing any inputs (i.e. user just hits enter when program asks for any input) and hence, string doesn't have any character. Extracting first character from blank string throws this error.

The solution will be to check for empty string (using length() method) before executing charAt(0).

Darshan Mehta
  • 30,102
  • 11
  • 68
  • 102
-2

You have lots of problems here.

Here's how I'd do it. It's never too early to learn about decomposition and writing clean, readable code:

/**
 * Created by Michael
 * Creation date 3/4/2016.
 * @link https://stackoverflow.com/questions/35806509/java-while-do-while-loop-with-users-decision-to-run-program-again/35806638?noredirect=1#comment59284245_35806638
 */

import java.text.NumberFormat;
import java.util.Scanner;

public class BurgerKing {

    public static final int MAX_ATTEMPTS = 3;
    public static final int MIN_QUANTITY = 1;
    public static final int MAX_QUANTITY = 15;
    public static final NumberFormat PRICE_FORMAT = NumberFormat.getCurrencyInstance();

    public static void main (String[] args){

        Scanner keyboard = new Scanner(System.in);
        String answer;
        do {
            System.out.println("Welcome!  Please place your order");
            int quantity = getBurgerQuantity(keyboard);
            double price = getBurgerPrice(keyboard);
            System.out.println(String.format("Your total is: %s", PRICE_FORMAT.format(quantity*price)));
            System.out.print("Another order? [Y/N]: ");
            answer = keyboard.nextLine();
        } while ("Y".equalsIgnoreCase(answer));
    }

    public static boolean isValidQuantity(int quantity) {
        return (quantity >= MIN_QUANTITY && quantity =< MAX_QUANTITY);
    }

    public static int getBurgerQuantity(Scanner scanner) {
        int numBurgers;
        int attempts = 0;
        do {
            System.out.print("How many burgers would you like? ");
            numBurgers = Integer.parseInt(scanner.nextLine());
        } while (!isValidQuantity(numBurgers) && (++attempts < MAX_ATTEMPTS));
        if (attempts == MAX_ATTEMPTS) throw new IllegalArgumentException(String.format("%d attempts is too many", attempts));
        return numBurgers;
    }

    public static double getBurgerPrice(Scanner scanner) {
        String price;
        System.out.print("Name your burger price: ");
        price = scanner.nextLine();
        return Double.parseDouble(price);
    }
}
duffymo
  • 305,152
  • 44
  • 369
  • 561
  • Thank you for help! After trying the code out it still gives me the message : Exception in thread "main" java.util.InputMismatchException and does not start it again. – Dany Mar 04 '16 at 22:45
  • 1
    The code that I posted is a self contained, running application. Yours will have to change. Try taking out that charAt call and simply compare the string you get in the input. My code works. – duffymo Mar 04 '16 at 23:20
  • 3
    -1 Josh Bloch (and many other people, me included) strongly advocate against introducing user-defined marker exception types for handling exceptions that are essentially non-custom in their behaviour. In this case, your `TooManyAttemptsException` is just a code smell, making the code unnecessarily lengthy and complicated - it has little semantic value; doing a `throw new IllegalStateException(attempts + ` attempts is too many!`)` is a lot better solution in this case (also, why `String.format` instead of `+` in this particular case? it's neither faster nor more readable) –  Mar 05 '16 at 13:23
  • @duffymo related: http://stackoverflow.com/a/27064/719662 , http://allenlsy.com/NOTES-of-Effective-Java-8-Exceptions/#60.-favor-the-use-of-standard-exceptions –  Mar 05 '16 at 13:25
  • Fair enough, thank you. Why String format? I appreciate the formatting when I want it. – duffymo Mar 05 '16 at 13:27
  • 1
    is concatenating Strings really a formatting action? I wouldn't say so; if you'd, for example, require a custom formatting on the number - I'd agree on using `format`; yet simple `number + " " + someString` is the exact use case of `+` String operator, not format itself. As a side note: IMO it should be `IllegalStateException` rather thatn `IllegalArgumentException`, since the amount of attempts is a function state, not an argument. –  Mar 05 '16 at 13:29