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

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

当我尝试 运行 程序时,它给我一个 plainPizza 尚未初始化的错误。

我已经尝试在它的循环之外初始化它 普通披萨 = getPlain() 但我不希望 getPlain 方法重复(这是我这样做时发生的情况)。我只想让它直接进入 checkOut 方法。

这是我的代码现在的样子:

`

    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; 是您的变量已声明初始化 正在为变量赋值。您在循环外声明了一个变量,但没有对其进行初始化。因此,当您在循环外使用它时,您的编译器会抛出错误 plainPizza has not been initialized.

int plainPizza = 0 处初始化一个值,您的代码应该很容易通过。

你只需要初始化变量 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);

如果您希望普通披萨的值不为 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);