Scanner keeps skipping input whist using nextInt() and loops

后端 未结 5 1224
情深已故
情深已故 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:44

    scan.nextLine();
    

    Put this piece of code inside your catch block, to consume the non integer character along with the new line character which is stays in the buffer(hence, infinitely printing the catch sysout), in the case where you've given a wrong input.

    Ofcourse, there are other cleaner ways to achieve what you want, but I guess that will require some refactoring in your code.

提交回复
热议问题