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
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.