0

I am programming a simulated online banking client in java. I need the ability (or an alternative) to be able to continue from a label. This is a snippet from my code so far.

    Main:
    {
    for ( ; ;) {
    System.out.println("Welcome to Tamarin© online banking!");
    System.out.println("Select register or login:");

    choice = scan.nextLine();

    if (choice.equalsIgnoreCase("register")) {
        register:
        {
        System.out.println("Welcome to register! Please type your username:");
        userreg = scan.nextLine();

        if (accounts.contains(userreg)) {
            System.out.println("Username taken! Try again.");
            continue register;

Java is giving me a "continue cannot be used outside of loop" error. Any ideas as to (if the registration fails) I could bring the user back to the last step ('registration' label)? And if not, how could I get this code to work?

(I obviously have closing braces down at the end).

lumpychum
  • 57
  • 8

2 Answers2

0

Well you shouldn't be using a goto in the first place (which currently doesn't exist in Java), the reason for this being that using labels promotes badly structured and difficult to maintain code (also called spaghetti code).

Instead you should add a nameTaken boolean and loop while it is true.

while(nameTaken) {
    System.out.println("Welcome to register! Please type your username:");
    userreg = scan.nextLine();

    if (accounts.contains(userreg))
        System.out.println("Username taken! Try again.");
    else {
        // do stuff
        nameTaken = false;
    }
}
Adel Khial
  • 345
  • 4
  • 15
0

First of all, thanks for using labels and taking us all back to C programming from so long ago. Second, you can easily simulate the behavior you currently have with labels by using appropriately constructed loops, e.g.

do {
    System.out.println("Welcome to Tamarin© online banking!");
    System.out.println("Select register or login:");
    choice = scan.nextLine();

    if (choice.equalsIgnoreCase("register")) {
        do {
            System.out.println("Welcome to register! Please type your username:");
            userreg = scan.nextLine();

            if (!accounts.contains(userreg)) {
                System.out.println("Creating username " + userreg + " ...");
                break;
            }
            else {
                System.out.println("Username taken! Try again.");
            }
        } while (true);
    }

    // the rest of your logic goes here
} while (true);
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360