Files of numbers
The lines of a file are Strings, just like keyboard input. In a file of numbers, each line is turned into a number with Integer.valueOf (or Double.valueOf for decimals), and then the usual tools work: a sum, a count, the largest. This file has the millimeters of rain on each day of a week:
0
12
3
0
25
0
0import java.nio.file.Paths;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
int total = 0;
int dryDays = 0;
int wettest = 0;
try (Scanner scanner = new Scanner(Paths.get("rain.txt"))) {
while (scanner.hasNextLine()) {
int rain = Integer.valueOf(scanner.nextLine());
total += rain;
if (rain == 0) {
dryDays++;
}
if (rain > wettest) {
wettest = rain;
}
}
} catch (Exception e) {
System.out.println("Error: " + e.getMessage());
}
System.out.println("Total: " + total + " mm");
System.out.println("Dry days: " + dryDays);
System.out.println("Wettest day: " + wettest + " mm");
}
}
Total: 40 mm
Dry days: 4
Wettest day: 25 mmStarting wettest at 0 works because rain is never below zero. For values that can be negative, such as temperatures, start from the first value instead: read the numbers into a list, and start from numbers.get(0).
Empty lines
Files sometimes have empty lines, for example between groups of values or at the very end. An empty line isn't a number:
5200
7400import java.nio.file.Paths;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
int total = 0;
try (Scanner scanner = new Scanner(Paths.get("steps.txt"))) {
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
total += Integer.valueOf(line);
}
System.out.println("Steps: " + total);
} catch (Exception e) {
System.out.println("Error: " + e.getMessage());
}
}
}
Error: For input string: ""Integer.valueOf("") threw a NumberFormatException, and the catch block caught it, as it catches any exception in the try block. The reading stopped at the empty line. To skip empty lines instead, check each line before turning it into a number, and go on to the next round with continue:
String line = scanner.nextLine();
if (line.isEmpty()) {
continue;
}
total += Integer.valueOf(line);
With that check, the program prints Steps: 12600.