【发布时间】:2023-03-23 05:10:02
【问题描述】:
我正在用Java编程,但我不明白如何使用break;命令退出多个循环。
这是我尝试过的一些代码:
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 上看到的问题并没有真正帮助我理解。提前致谢!
【问题讨论】:
-
你的嵌套循环在哪里?
-
@Lashane 我已经看过了,但情况不同(使用 for 循环)。
-
所有循环都一样
-
当涉及到
break时,所有循环的行为都相同 -
您只显示了一个循环,并且您没有检查输入是否等于 2,因此您可以从那里开始。