-2

I have to get 1 to 3 answer if user puts invalid option do while should re run but problem is its re running three times. like if I put answer in 1 to 3 its giving correct result on other number it reprint loop three times.

char choice;
public void mainMartfunc() throws java.io.IOException{

        do{
            System.out.println("Login as:");
            System.out.println("    1. Customer");
            System.out.println("    2. Employee");
            System.out.println("    3. Owner");
            choice = (char) System.in.read();
            } while(choice < '1' || choice>'3');
        switch(choice){

         case '1':
             System.out.println("\tCustomer Menu:");
             break;

         case '2':
             System.out.println("\tEmployee Menu:");
             break;

         case '3':
            System.out.println("\tOwner Menu:");
            break;
        }
}
maniarali
  • 31
  • 5

1 Answers1

2

When you press the enter key, two characters are generated: a carriage return '\r' and a line feed '\n'. And System.in.read() takes each character from the input, so you get three characters including the digit.

Trying using a Scanner instead. It will tokenize your input so you don't receive those whitespace characters.

java.util.Scanner input = new java.util.Scanner(System.in);

then change your choice assignment to something like this:

choice = input.next().charAt(0);
gknicker
  • 5,509
  • 2
  • 25
  • 41