while 循环跳过 switch cases 并执行 default

While loop skips switch cases and executes default

程序应该 运行 计算不同的形状,因为不同的情况嵌套在 while 循环中。代码如下:

package Lab_7;
import java.util.*;

public class compar {
    public static void main(String [] args){
        Scanner d = new Scanner(System.in);
        boolean start = true;


    while(start){
        System.out.print("Would you like to start the program?: ");
        String answer1 = d.nextLine();

        switch (answer1){
            case "yes":
                System.out.println("Which shape would you like to use to compute area/perimeter?: ");
                String answer2 = d.nextLine();  

                if(answer2.equals("circle")){           
                    try{
                        System.out.print("Enter radius: ");
                        int answer3 = d.nextInt();
                        Circle c = new Circle(answer3);
                        double area = c.computeArea();
                        double perimeter = c.computePerimeter();
                        System.out.println("Area = " + area + " & perimter = " + perimeter );
                        break;                          
                    }
                    catch(Exception e){
                        System.out.println("Error!");
                        break;
                    }
                }

            case "no":
                System.out.println("Program Terminating...");
                start = false;
                break;

            default:
                System.out.println("bug");
                continue;
            }
    }
    d.close();
}

}

然而,在 运行 第一次成功 运行 之后,程序应该循环回到开头(要求用户启动程序?)但是却发生了这种情况:

Would you like to start the program?: yes
Which shape would you like to use to compute area/perimeter?: 
circle

Enter radius: 10

Area = 314.16 & perimter = 62.832

Would you like to start the program?: bug

Would you like to start the program?: 

我可以使用一堆 if 语句,但我真的需要知道为什么在第一次成功后 运行,我的程序:

  1. 跳过所有case执行default语句,然后循环回到第一个print语句最后等待输入?

当您输入半径时,d.nextInt() 消耗下一个整数,但不消耗新行。

面积计算完成后,break语句结束switch语句。

然后行 String answer1 = d.nextLine() 消耗了 d.nextInt() 没有消耗的新行,这导致它执行默认情况,因为 answer1 既不是 "yes" 也不是"no".

continue 导致执行返回到 while 循环的开始,然后再次等待输入。

要修复它,请在获取半径输入后添加 d.nextLine()

int answer3 = d.nextInt();
d.nextLine(); //consumes the \n character

此外,您必须在 yes 的末尾添加一个 break。否则,用户可以输入 "yes",然后输入 "circle" 以外的其他内容,程序执行将失败并终止。