Read Data From Text File And Sum Numbers

前端 未结 8 1495
伪装坚强ぢ
伪装坚强ぢ 2020-12-21 13:59

I want to read in data from a text file which is full of integers and have the program print those integers out to the screen while summing them. This shouldn\'t be hard, b

8条回答
  •  再見小時候
    2020-12-21 14:44

    It throws an exception because you don't increment i in the loop. In case if the number of integers in the input file is unknown, you can use the Scanner.hasNextInt() method to check the presence of the next integer (or just use hasNext() to check for EOF).

    You can sum the numbers like in the code snippet below:

        ...
        int sum = 0;
        while(i++ < 25)
        {
            sum += aScanner.nextInt();
        }
    

    or

        ...
        int sum = 0;
        while(aScanner.hasNextInt())
        {
            sum += aScanner.nextInt();
        }
    

提交回复
热议问题