2015-11-30 22 views
-3

我使用Java進行編程,但我不明白如何使用break;命令退出多個循環。雙擊java

下面是一些代碼,我想:

while (true){ 
     System.out.println("\n\nBank Menu: \nWhat action do you want to perform(Enter a number)?\n\n1. Create a bank account \n2. Log in to a preexisting account \n3. Exit bank system"); 
     String action1 = scanner.next(); 
     if (action1.equals("1")) { 
      if(!(password==null)){ 
       if(createAccountTracker==1){ 
        createAccountTracker=0; 
        break; 
       } 
       System.out.println("Are you sure? Creating a new account will remove your preexisting account\n1.Yes\n2.Cancel"); 
       createaccount = scanner.next(); 

       if(createaccount.equals(2)) { 
        createAccountTracker=1; 
        break; 
       } 
      } 

      System.out.println("What will your account name be(One Word Only)?"); 
      accName = scanner.next(); 
      System.out.println("Please enter your account password: "); 
      passwordCheck1 = scanner.next(); 
      System.out.println("Please reenter your account password: "); 
      passwordCheck2 = scanner.next(); 
      if(passwordCheck1.equals(passwordCheck2)){ 
       password= passwordCheck2; 
       System.out.println("Your account has been made!\n\nThank you for creating an account!\nAccount name: " + accName + "\nPassword: " + password); 
       accBalance=0; 
      } 
      else{ 
       System.out.println("Error: Two passwords entered do not match. Please try again."); 
      } 
     } 

我試圖讓這個,如果他們進入2(取消),代碼會跳出兩個循環並回到銀行菜單。我在SO上看到的問題並沒有真正幫助我理解。提前致謝!

+2

你的嵌套循環在哪裏? –

+0

@Lashane我已經看到了這一點,但這是一個不同的情況(使用for循環)。 – babyguineapig11

+0

所有循環都相同 –

回答

4

可以打破2路的這樣:

outer: 
while(condition) { // while or for loops, same way 
    while(condition2) { 
     break outer; // break out of the 2 loops 
    } 
} 

// Other code 

的 「」 的標籤,標誌着局外人循環。

+0

一旦我使用break outer; ,它會跳出所有循環並轉到第一個循環? – babyguineapig11

+0

它將跳出兩個循環並執行任何代碼。 –

+0

我可以繼續嗎? – babyguineapig11