Read Data From Text File And Sum Numbers

前端 未结 8 1456
伪装坚强ぢ
伪装坚强ぢ 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:31

    You never increment i, so the while loop continues beyond the end of the file. As for summing, do something like this.

    static void addstuff(Scanner aScanner) {
            int sum = 0;
    
            while (aScanner.hasNextInt()) {
                sum += aScanner.nextInt();
            }
    
            System.out.println(sum);
    }
    

    This will run until hasNextInt() returns false, which occurs when the next item the scanner sees isn't an integer. This could be non-numeric input or the end of the file. This means you're no longer limited to 25 integers - it'll read as many as it can before stopping.

提交回复
热议问题