0

When I try to run the program it gives me an error that plainPizza has not been initialized.

I already tried to initialize it outside its loop with plainPizza = getPlain() but I do not want the getPlain method to repeat (which is what happened when I did that). I just want it go straight to the checkOut method.

Here is what my code looks like right now:

`

    int plainPizza, customerOption;
    
    System.out.println("Enter 2 to order or 1 to exit: ");
  
    customerOption = keyboard.nextInt();
    
    while (customerOption != 1)
    {
        plainPizza = getPlain();
        System.out.println("Enter 2 to order or 1 to exit: ");
        customerOption = keyboard.nextInt();
    }
    checkOut(plainPizza);
}`
mojava
  • 35
  • 4
  • 1
    Image seems not to be working, please put code directly in your post in plain text. – ELinda Nov 14 '20 at 18:16
  • There's `while(cond) { ... }` and `do { ... } while(cond);` and of course for-loops. Choose whichever is appropriate. Also try to always include your code in your questions directly. – BeyelerStudios Nov 14 '20 at 18:18
  • Int plainPizza=0, initialize the variable while declaring it, compiler complains as the variable will only be initialized based on the loop condition true, otherwise – JineshEP Nov 14 '20 at 18:26
  • If the customer presses `2` multiple times, you're going to call getPlain() multiple times, losing all but the most recent return value. – jarmod Nov 14 '20 at 18:30
  • I edited my code into my question directly. Thank you for letting me know. And I just tested `plainPizza = 0` and it works. Thank you! – mojava Nov 14 '20 at 18:32

2 Answers2

1

int plainPizza; is your variable being declared. Initialization is assigning a value to a variable. You are declaring a variable outside the loop but not initializing it. Thus, when you use it outside the loop, your compiler shoots out the error plainPizza has not been initialized.

Initialize a value at int plainPizza = 0 and your code should pass easily.

0

you just have to initialize the variable plainPizza, for example:

int plainPizza=0, customerOption;

        System.out.println("Enter 2 to order or 1 to exit: ");

        customerOption = 2;

        while (customerOption != 1)
        {
            plainPizza = 7;
            System.out.println("Enter 2 to order or 1 to exit: ");
            customerOption = 1;
        }
        System.out.println(plainPizza);

if you want that plain pizza has a value different than 0, you can do this:

    int plainPizza=0, customerOption;

    System.out.println("Enter 2 to order or 1 to exit: ");

    customerOption = 2;

    while (customerOption != 1 && plainPizza!=0)
    {
        plainPizza = 7;
        System.out.println("Enter 2 to order or 1 to exit: ");
        customerOption = 1;
    }
    System.out.println(plainPizza);