Tuesday 6 November 2018

loops - Double break java




I am programming with Java, and I do not understand how to use the break; command to get out of more than one loop.



Here is some code that I tried:




    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.");
}
}


I am trying to make it so that if they enter 2(cancel), the code will break out of the two loops and go back to the bank menu. The question I saw on SO did not really help me understand. Thanks in advance!


Answer



You can break out of 2 loops this way:



outer: 

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

// Other code


The "outer" label marks the outsider loop.



No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...