用int变量控制Do ... While()循环无法正常工作

时间:2019-09-30 23:44:59

标签: java java.util.scanner

编辑:问题是我没有在变量外声明变量

我的循环无法将int解析为变量。

不能尝试其他类型的变量,它必须是整数。

        do {
            System.out.println("Would you like to add any snacks? ");
            System.out.println("1: ($5) Large Popcorn");
            System.out.println("2: ($0) Nothing Else");
            int snackChoice = input.nextInt();

            System.out.println("How many of option " + snackChoice + " would you like? ");
            System.out.println("1: One");
            System.out.println("2: Two");
            System.out.println("3: Three");
            System.out.println("4: Four");
            System.out.println("5: Five");
            int snackAmount = input.nextInt();

            switch (snackChoice) { 
            case 1: 
                cost = cost + 5 * snackAmount;
                System.out.println("Your total before tax will be: $" + cost + (5 * snackAmount)); 
            break;

            default: 
                System.out.println("Not a valid option."); 
            break;

            }
        }
        while(snackChoice != 9);

其余:https://pastebin.com/Y6Xd24D0

有效。实际结果:不是。

错误:snackChoice cannot be resolved to a variable

1 个答案:

答案 0 :(得分:2)

do...while循环是一个代码块,这意味着无法在该块外部看到其中定义的变量。 while部分在块之外,因此看不到snackChoice

只需在int snackChoice之前之前定义do...while不在其中

int snackChoice;
do {
    System.out.println("Would you like to add any snacks? ");
    System.out.println("1: ($5) Large Popcorn");
    System.out.println("2: ($0) Nothing Else");
    snackChoice = input.nextInt();

    System.out.println("How many of option " + snackChoice + " would you like? ");
    System.out.println("1: One");
    System.out.println("2: Two");
    System.out.println("3: Three");
    System.out.println("4: Four");
    System.out.println("5: Five");
    int snackAmount = input.nextInt();

    switch (snackChoice) { 
    case 1: 
        cost = cost + 5 * snackAmount;
        System.out.println("Your total before tax will be: $" + cost + (5 * snackAmount)); 
    break;

    default: 
        System.out.println("Not a valid option."); 
    break;

    }
}
while(snackChoice != 9);