Question

boolean acceptPcode=true;
boolean acceptQty=false;
int Qty=0;
List<Integer> purchasedProdQty=new ArrayList<>();

while(acceptPcode==true && acceptQty==false){
        do{
            try{
                 System.out.print("Enter Qty: ");
                    Qty=sc.nextInt();
                    acceptQty=true;                 
              }catch(InputMismatchException ime){
                    System.out.println("Invalid quantity please enter a number!");
                    acceptQty=false;
              }

                    if(acceptQty==true)
                    purchaseProdQty.add(Qty);

           }while(acceptQty==false);

} 

my question is that when i enter a letter it goes in an infinity loop and it doesn't prompt the user to enter a quantity ....which is

Enter Qty: Invalid quantity please enter a number!

Enter Qty: Invalid quantity please enter a number!

Enter Qty: Invalid quantity please enter a number!......

Was it helpful?

Solution

You forgot to read the \n (or \r\n) characters that are from the next line. In your current code, the scanner is waiting for an int input, bu the current next input is this break line char. Just add sc.nextLine() in your code to consume the break line char:

Qty=sc.nextInt();
sc.nextLine();
acceptQty=true;

OTHER TIPS

From what I can gather it seems your scanner(sc) is throwing an exception. This causes acceptQty to constantly be false keeping you stuck in your inner do-while loop.

You need to consume any illegal characters in the exception block otherwise they won't be consumed by the Scanner#nextInt method call causing the loop to repeat itself indefinitely:

} catch(InputMismatchException ime) {
    System.out.println
      ("Invalid quantity: " + sc.nextLine() + " please enter a number ");
    ...
}

You are getting exception while reading out of sc and so it always go into infinity loop. Can you paste what's the value assiged in sc?

I believe you're doing this all wrong. Your method of validation is very obscure and can be simplified. Suppose you have the following method:

public int readNumber(final String prompt, final Scanner scanner){
    System.out.println(prompt);
    try{
        return scanner.nextInt();
    }catch(Exception ex){
        System.err.println("Enter a valid number");
        return readNumber(prompt, scanner);
    }
}

This method will print out the prompt (the first argument) and read input from the provided Scanner (the second argument). If the user enters something that can't be parsed as an int, it will invoke the same method (recursion).

Take out both of your loops and when you want to read an int from your Scanner, do something like:

int value = readNumber("Enter a quantity", sc);

You know for sure that Integer.MAX_VALUE >= value >= Integer.MIN_VALUE

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top