繁体   English   中英

在Switch语句的中间终止while循环

[英]Terminating while loop in middle of Switch Statment

我想在用户按2退出时终止我的while循环,但是如果用户按2却没有退出,我又进入了循环,请帮助我

int count = 1;

while(count <=3) {

  System.out.println(" Enter any option");
  System.out.println(" Enter 1 for addition");
  System.out.println(" Enter 2 for exit");

  Scanner input = new Scanner (System.in);

  int option = input.nextInt();
  if(option==2) {
    System.out.println("Thank you for using app");
  }
  else
    switch(option) {
      case 1 :
         System.out.println("welcome to addtion");
         int sum;
         System.out.println("Enter first number");
         int x = input.nextInt();
         System.out.println("Enter second number");
         int y = input.nextInt();
         sum=x+y;
         System.out.println(sum);
      break;
      case 2 : 
         System.out.println("do you want to exit ? ");
      break;

    }   
 }

也许您的循环条件应该是:

 while (option != 2)

您当前的状态while (count <=3)没有多大意义,因为count不会在循环内更新。

您可以使用标记的休息时间

input: while( count <=3) {
...
...
switch( option) {
...
case 2:
...
    break input; // break the outer while loop
...

但是我认为通常最好将while循环封装在一个方法中,然后在这种情况下“返回”。

您的while循环条件是可疑的,但是更改一行就足够了。

if(option==2) { 
    System.out.println("Thank you for using app");
    break;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM