循环跳过切换案例并执行默认

时间:2017-03-02 04:46:41

标签: java while-loop switch-statement case 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. 跳过所有情况并执行默认语句,然后循环回第一个print语句,最后等待输入?

1 个答案:

答案 0 :(得分:0)

输入半径时,d.nextInt()会消耗下一个int,但不会消耗新行。

计算区域后,break语句终止switch语句。

然后,行String answer1 = d.nextLine()会占用d.nextInt()未使用的新行,这会导致它执行默认情况,因为answer1既不是"yes",也不是"no" 1}}。

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

要解决此问题,请在获取半径输入后添加d.nextLine()

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

此外,您必须在“是”案例的末尾添加break。否则,用户可以输入"yes",然后输入"circle"以外的其他内容,程序执行将无效并终止。