Scanner keeps skipping input whist using nextInt() and loops

后端 未结 5 1223
情深已故
情深已故 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条回答
  •  半阙折子戏
    2020-12-12 04:57

    Use the following:

    while (!capacityCheck) {
            System.out.println("Capacity");
            String input = scan.nextLine();
            try {
                capacity = Integer.parseInt(input );
                capacityCheck = true;
            } catch (NumberFormatException e) {
                System.out.println("Capacity must be an integer");
            }
        }
    

提交回复
热议问题