Infinite loop on Scanner.hasNext, reading from a file

后端 未结 3 1492
野的像风
野的像风 2021-01-22 17:32

I\'m apparently facing an infinite loop on while(input.hasNext()) , as in following code

File file = new File(\"data.txt\");
Scanner input = new Sca         


        
3条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-22 17:44

    Seems like scanner is reading a non int value from your file and when it does , while(input.hasNext()) will always be true because there is something as an input to scanner but it is not int. So scanner skips reading this non-int value in the inner if(input.hasNextInt()) check.

    So scanner does not proceed beyond this element and always return true.

    If you want to sum up all the integers in your file then you should modify your code to below:

    while(input.hasNext()) {            
                if(input.hasNextInt()) {                
                    sum += input.nextInt();
                }
                else
                    input.next();
            }
    

    Just read the non integer elements when scanner encouters it. Hope this clarifies.

提交回复
热议问题