How do you validate a String to make the program continue or not?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Cleo Millet
    New Member
    • Oct 2011
    • 7

    How do you validate a String to make the program continue or not?

    I'm not sure if this should be in two separate posts or not. So, I apologize ahead of time if this is the case. However, since I'm trying to do one thing here with two conflicting methods, I thought it should go together.

    I'm trying to have a simple 'Do you want to continue?' question at the end of a program. However, I want to validate that information so there are no mistakes. I know there are a TON of ways of doing it - I've been googling it for a week now but most of the codes I've found either don't make any sense to me or simply don't work.

    This is the "prototype" I've been working with. I can't figure out what's wrong with it.

    Code:
    		while (!choice.equalsIgnoreCase("y") && !choice.equalsIgnoreCase("n")) {
    			System.out.println("Error.  Do you wish to continue? (y/n): ");
    			choice = sc.next();
    			System.out.println();
    		}

    I'd really rather not resort to a long if/else statement for this - although I have worked one out, except for on thing. I understand that it's not good coding practice to use BREAK to exit a program. How else would you do it though?

    Code:
    System.out.println("Do you want to continue? (y/n): ");
    String choice2 = sc.next();
    System.out.println();
    				 
    if (choice2.equals("y")) {
    continue;
    }
    else if (choice2.equals("n")) {
    break;
    }
    else {
    System.out.println("Error. Create an Employee or a Customer (e / c): ");
    }
    Help?
Working...