My professor tends to do the following to get a number from a user:
Scanner scanner = new Scanner(System.in);
Integer.parseInt(scanner.nextLine());
What are the advantages as opposed to simple execution scanner.nextInt()?
java.util.Scanner.java has the following in it:
public int nextInt() {
return nextInt(defaultRadix);
}
public int nextInt(int radix) {
if ((typeCache != null) && (typeCache instanceof Integer)
&& this.radix == radix) {
int val = ((Integer)typeCache).intValue();
useTypeCache();
return val;
}
setRadix(radix);
clearCaches();
try {
String s = next(integerPattern());
if (matcher.group(SIMPLE_GROUP_INDEX) == null)
s = processIntegerToken(s);
return Integer.parseInt(s, radix);
} catch (NumberFormatException nfe) {
position = matcher.start();
throw new InputMismatchException(nfe.getMessage());
}
}
As I can see, ScannerInteger.parseInt () also calls, in addition to additional focusing. Significant performance gains achieved simply Integer.parseInt(scanner.nextLine())? Are there any flaws, on the other hand?
How about scanning through a file with a significant amount of data, and not from user input?
source
share