簡體   English   中英

無法跳出java中的while循環

[英]Cannot break out of while loop in java

我無法跳出 while 循環,請查看並推薦我怎么做

public class Admin {
boolean exit=false;
public Admin(){
    while (!exit){
    printInstructions();
    }
}
public void printInstructions(){
    System.out.println("check 1 to print hi");
    System.out.println("check 2 to exit");
    Scanner scanner=new Scanner(System.in);
    int choice=scanner.nextInt();
    scanner.nextLine();
    choose(choice);
}
public void choose(int choice){
    switch(choice){
        case 1:
            System.out.println("hi");
            break;
        case 2:
            exit=true;
            break;
    }
}
}

我希望代碼停止執行,但相反它運行了很多次。 但是while循環一遍又一遍地運行。 我想知道為什么?

在兩個switch語句中添加breakreturn以完全離開 switch。 之后它將返回while語句,評估boolean exit並在為false時退出loop

 public void choose(int choice){
    switch(choice){
      case 1:
        System.out.println("hi");
        break;
      case 2:
        exit=true;
        break;
    }
  }

您可以嘗試將代碼分解為更小的方法/函數。 但是如果您的功能相互交互會更好。 為了使您的函數成為可能,作為執行的結果,您的函數必須返回一些值:

// returns exit flag
public bool choose(int choice){
    switch(choice){
        case 1:
            System.out.println("hi");
            return false;
        case 2:
            return true;
    }
}

// print instructions and return the choose
public int printInstructions(){
    System.out.println("check 1 to print hi");
    System.out.println("check 2 to exit");
    Scanner scanner=new Scanner(System.in);
    int choice=scanner.nextInt();
    scanner.nextLine();
    return choice;
}


public Admin(){
    while (!exit){
      int result = printInstructions();
      exit = choose(result);
    }
}

我在瀏覽器中編寫代碼,所以它仍然可能有一些小錯誤。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM