Infinite loop on Scanner.hasNext, reading from a file

后端 未结 3 1588
野的像风
野的像风 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:38

    You do not need to double checking on content. this should work:

       File file = new File("data.txt");
        Scanner input = new Scanner(file);
    
        int sum = 0;
    
        while(input.hasNextInt()) {
                sum += input.nextInt();
        }
        System.out.println(sum);
    

    Hope this helps.

提交回复
热议问题