Going out from a switch inside a do while, but without a boolean, it's possible? Java

Viewed 79

So the code is about giving a limit of inputs in a do while. In this case you have 3 oportunities to continue. After that the do while stops, also you have the oportunitie to stop just presing any key plus enter, but also when you start, do you have the oportunitie (here enters the switch) to exit the program. The problem or where I get stuck is here.

That maybe it's possible without a boolean, or maybe changing or adding something that I don't yet know. Sorry I try to find an answer but all I saw it's about going out a while loop whith boolean or so. Not like this.

    Scanner kb = new Scanner(System.in);
    // c = continue
    char c;
    // attempt to limit the input to 3 times
    int attempt = 3;
    // option = op
    int op = 0;

    do {
        do{
            System.out.println("Choose continue[0] or go out[1].");
            while  (!kb.hasNextInt()) {
                kb.nextLine();
                System.out.println("It's not a number.");                   
            }
            op = kb.nextInt();
        } while ( op <= -1 || op >= 2 );

        switch (op) {
        case 0:
            System.out.println("Continue!");
            break;
        case 1:     //here I tried; attempt = -1  
            break;  //is where I think it needs to be something
        default:
            break;
        }

        System.out.println("Do you wanna try again,"+attempt+" less?[c]+enter\n"
                + "Any other key + enter to exit.");
        c = kb.next(".").toUpperCase().charAt(0);
        attempt--;
    } while ( attempt > 0 && ( c == 'C' ) );
            //here also to put !( op == 0 )
    kb.close();
4 Answers

I think you can do this pretty easily without a case switch by using a method:

    static Scanner kb = new Scanner(System.in);

public static void main(String args[]){
     if(getContinueOption(3)){
         //do what you want to do
     }
}

private static boolean getContinueOption(int attempts) {
    System.out.println("Would you like to continue? Y[1] : N[0]");
    while(attempts > 0){
        int input = kb.nextInt();
        if(input == 1){
            return true;
        }
        attempts--;
        System.out.println( (attempts == 0)? "Ok :(" : "Are you sure?");
    }
    return false;
}

You only need to ask for continuation if user chooses 0.

Scanner kb = new Scanner(System.in);
// c = continue
char c = 'a';
// attempt to limit the input to 3 times
int attempt = 3;
// option = op
int op = 0;

do {
    do{
        System.out.println("Choose continue[0] or go out[1].");
        while  (!kb.hasNextInt()) {
            kb.nextLine();
            System.out.println("It's not a number.");
        }
        op = kb.nextInt();
    } while ( op <= -1 || op >= 2 );

    switch (op) {
        case 0:
            System.out.println("Continue!");
            System.out.println("Do you wanna try again,"+attempt+" less?[c]+enter\n"
                    + "Any other key + enter to exit.");
            c = kb.next(".").toUpperCase().charAt(0);
            attempt--;
            break;
        case 1:
            attempt = -1;
            break;
        default:
            break;
    }
} while ( attempt > 0 && ( c == 'C' ) );
kb.close();

This question is a little hard to understand, but I think what you want is...

        Scanner kb = new Scanner(System.in);
    // c = continue
    char c;
    // attempt to limit the input to 3 times
    int attempt = 3;
    // option = op
    int op = 0;

    the_loop:
    do {
        do{
            System.out.println("Choose continue[0] or go out[1].");
            while  (!kb.hasNextInt()) {
                kb.nextLine();
                System.out.println("It's not a number.");                   
            }
            op = kb.nextInt();
        } while ( op <= -1 || op >= 2 );

        switch (op) {
        case 0:
            System.out.println("Continue!");
            break;
        case 1:     //here I tried; attempt = -1  
            break the_loop;  //is where I think it needs to be something
        default:
            break;
        }

        System.out.println("Do you wanna try again,"+attempt+" less?[c]+enter\n"
                + "Any other key + enter to exit.");
        c = kb.next(".").toUpperCase().charAt(0);
        attempt--;
    } while ( attempt > 0 && ( c == 'C' ) );
            //here also to put !( op == 0 )
    kb.close();

Note the_loop and break the_loop;

It's actually simpler than that and avoids the use of if statements, although I am not sure why you would do it this way in real life, it's a good exercise to go over concepts.

Let's look at the implementation first:

import java.util.*;
import java.lang.*;

class SillyEnforcer {
    public static void main(String[] args) {
        Scanner kb = new Scanner(System.in);
        char c = 'C';
        int attempt = 3;
        int op = 0;

        while(attempt > 0 && c == 'C') { // attempt loop
            do {

                System.out.println("Enter 0 to continue, 1 to exit");
                while  (!kb.hasNextInt()) {
                    kb.nextLine();
                    System.out.println("Not a number, try again.");
                }
                op = kb.nextInt();
                switch(op) {
                    case 0:
                        continue;
                    case 1:
                        op = -1;
                        break;
                    default:
                        System.out.println("Number can only be 0 or 1.");
                        op = 0; // positional trickery
                        continue;
                }
            } while(op != -1);

            System.out.println("Do you wanna try again, ("+ attempt + " attempt" +
                    ((attempt > 1) ? "s" :  "") + " left) ? C<ENTER> to continue\n"
                                      + "Any other key<ENTER> to exit");
            c = kb.next(".").toUpperCase().charAt(0);
            attempt = attempt - ((c == 'C') ? 1 : 0);
        }
    }
}

Inner magic

Notice that by using continue for case 0 and reassigning op=-1 for case 1 we can manage the messages correctly and by assigning op=0 in default: we take care of the edge case where a clever person enters -1 as the integer above.

And notice that we make the while statement exit on op == -1. This makes the flag which exits while separate from the input which gives you the magic you need to cover all cases. -1 will never happen by input, (we fix that in default) and 0 is the only thing that sets op to -1. All other cases continue the inner while loop.

'C' for continue magic

We only want to decrease attempt if someone actually wants to continue otherwise we exit anyways, it does not matter here but you can extend this logic to change the question to "do you want to exit [Y/n]" and loop if answer is not a 'Y' or an 'n' while decreasing attempt only on a valid answer of 'Y'

Related