Scanner keeps skipping input whist using nextInt() and loops

后端 未结 5 1200
情深已故
情深已故 2020-12-12 04:13

I am using a while loop to make sure that the value entered to a scanner object is an integer as such:

while (!capacityCheck) {
        try {
            Sys         


        
5条回答
  •  萌比男神i
    2020-12-12 04:40

    Try putting this at the end of the loop -

    scan.nextLine();
    

    Or better to put it in the catch block.

        while (!capacityCheck) {
            try {
                System.out.println("Capacity");
                capacity = scan.nextInt();
                capacityCheck = true;
            } catch (InputMismatchException e) {
                System.out.println("Capacity must be an integer");
                scan.nextLine();
            }
        }
    

提交回复
热议问题