Let's assume for a second that under each name they can be a variable number of numerical values. What we want to do is, while each line is number, keep adding them together and keep track of the number of lines we've read and when the line becomes a String
probably print it out and setup for the next sequence.
I honestly think that people think that Scanner
is only useful for reading user input or a file and forget that they can use multiple Scanner
s to parse the same content (or help with it)
For example. I set up Scanner
to read each line of the file (as a String
). I then setup a second Scanner
(for each line) and test to see if it's an int
or not and take appropriate action, for example...
import java.util.Scanner;
public class Test {
public static void main(String[] arg) {
// Just beware, I'm reading from an embedded resource here
Scanner input = new Scanner(Test.class.getResourceAsStream("/resources/Test.txt"));
String name = null;
int tally = 0;
int count = 0;
while (input.hasNextLine()) {
String line = input.nextLine();
Scanner parser = new Scanner(line);
if (parser.hasNextInt()) {
tally += parser.nextInt();
count++;
} else {
if (name != null) {
System.out.println(name + "; tally = " + tally + "; average = " + (tally / (double) count));
}
name = parser.nextLine();
tally = 0;
count = 0;
}
}
if (name != null) {
System.out.println(name + "; tally = " + tally + "; average = " + (tally / (double) count));
}
}
}
which based on your example data, prints something like...
James; tally = 821; average = 273.6666666666667
Kyle; tally = 1505; average = 501.6666666666667