【问题标题】:While loop skips switch cases and executes default [duplicate]While循环跳过切换案例并执行默认[重复]
【发布时间】:2017-03-02 04:46:41
【问题描述】:

程序应该为不同的形状运行计算,因为不同的情况嵌套在一个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. 跳过所有情况并执行默认语句,然后循环回到第一个打印语句,最后等待输入?

【问题讨论】:

  • 因为这个in.nextInt();包含一个字符串字符\n所以它会跳过下一个in.nextLine()你想尝试把in.nextLine()放在in.nextInt()之后
  • case "yes" 末尾缺少 break 语句。
  • @Smit 你把它完全背对了。 nextInt() 确实 包含换行符,并且将 跳过下一个nextLine(),因此要求是通过添加nextLine() 调用来使用换行符。你的解释毫无意义。
  • @EJP 感谢您的纠正。感谢您的反馈。下次会注意的。

标签: java while-loop switch-statement case default


【解决方案1】:

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

计算完面积后,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"以外的其他内容,程序执行将进入no case并终止。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-04-01
    • 2015-01-28
    • 1970-01-01
    • 1970-01-01
    • 2017-04-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多