简体   繁体   English

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

[英]Terminating while loop in middle of Switch Statment

I want to terminate my while loop when user press 2 for exit but I entered loop again if user press 2 it did not exit please help me about it thanks 我想在用户按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;

    }   
 }

Perhaps your loop's condition should be : 也许您的循环条件应该是:

 while (option != 2)

Your current condition - while (count <=3) doesn't make much sense, since count is not updated inside the loop. 您当前的状态while (count <=3)没有多大意义,因为count不会在循环内更新。

You could use a labeled break 您可以使用标记的休息时间

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

But I think it's generally better to encapsulate the while loop in a method and 'return' in cases like that. 但是我认为通常最好将while循环封装在一个方法中,然后在这种情况下“返回”。

Your while loop condition is suspect but a one line change would suffice. 您的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