我会说,使用泛型方法,结合Java 8中引入的
functional interfaces。
private T read(Predicate hasVal, Function nextVal) {
T value = null;
while (value == null) {
if (hasVal.test(scanner)) {
value = nextVal.apply(scanner);
} else {
scanner.next();
}
}
return value;
}
调用代码变为:
read(Scanner::hasNextInt, Scanner::nextInt);
read(Scanner::hasNextDouble, Scanner::nextDouble);
read(Scanner::hasNextFloat, Scanner::nextFloat);
// ...
所以readInteger()方法可以改编如下:
private Integer readInteger() {
return read(Scanner::hasNextInt, Scanner::nextInt);
}