Search code examples
javajgrasp

How can I use the variable I initialized outside its loop?


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);
}`

Solution

  • 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.