简体   繁体   English

如何使用我在其循环外初始化的变量?

[英]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.当我尝试运行该程序时,它给我一个 plainPizza 尚未初始化的错误。

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).我已经尝试使用 plainPizza = getPlain() 在其循环外初始化它,但我不希望 getPlain 方法重复(这是我这样做时发生的情况)。 I just want it go straight to the checkOut method.我只希望它 go 直接到 checkOut 方法。

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.因此,当你在循环外使用它时,你的编译器会抛出错误plainPizza has not been initialized.

Initialize a value at int plainPizza = 0 and your code should pass easily.int plainPizza = 0处初始化一个值,您的代码应该很容易通过。

you just have to initialize the variable plainPizza, for example:你只需要初始化变量 plainPizza,例如:

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:如果您希望普通披萨的值不同于 0,您可以这样做:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM