简体   繁体   中英

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

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.

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

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