簡體   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