Ola*_*oja 6 java performance integer user-input java.util.scanner
我的教授倾向于做以下事情来从用户那里得到一个数字:
Scanner scanner = new Scanner(System.in);
Integer.parseInt(scanner.nextLine());
Run Code Online (Sandbox Code Playgroud)
与简单的做法相比,有什么好处scanner.nextInt()?
java.util.Scanner.java 有以下内容:
public int nextInt() {
return nextInt(defaultRadix);
}
public int nextInt(int radix) {
// Check cached result
if ((typeCache != null) && (typeCache instanceof Integer)
&& this.radix == radix) {
int val = ((Integer)typeCache).intValue();
useTypeCache();
return val;
}
setRadix(radix);
clearCaches();
// Search for next int
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(); // don't skip bad token
throw new InputMismatchException(nfe.getMessage());
}
}
Run Code Online (Sandbox Code Playgroud)
在我看来,Scanner除了额外的hocus pocus之外,还调用Integer.parseInt()本身.做简单的性能有显着提升Integer.parseInt(scanner.nextLine())吗?另一方面有任何缺点吗?
扫描包含大量数据而不是用户输入的文件时怎么样?
The*_*ind 11
有2个观察结果:
myScannerInstance.nextInt()新行字符后面的叶子,因此,如果您调用 nextLine()after nextInt(),nextLine()则将读取新行字符而不是实际数据.所以,你必须在加入那个晃来晃去的新行角色nextLine()后添加另一个.不留下新的线条字符.nextInt()nextLine()代码:
int age=myScannerInstance.nextInt();
String name = myScannerInstance.nextLine();// here the actual name will not be read. The new line character will be read.
Run Code Online (Sandbox Code Playgroud)
nextInt()将再次回到底层流并阅读.IO调用需要时间(昂贵).它将进行大量检查以获得下一个整数.nextLine()将只执行一次这样的检查..因此,如果你调用nextLine()一次并读取5个整数(作为单行字符串),拆分它们并将它们解析为整数(使用Integer.parseInt()),它将比单独读取每个int更快更有效.使用nextLine()+ parseInt()将在运行非常大的循环时为您带来巨大的性能优势.
用法:
使用nextInt()为您提供了额外的优势,如果输入文本不是整数,您将获得异常.示例123被接受.. 123sdsa将抛出一个InputMismatchException.所以,你可以抓住它并适当地处理它.
使用nextLine()将读取整行,因此,它将读取整个String sada1231,NumberFormatException如果它无法将String解析为数字则失败.您将不得不处理该异常.
一般来说,一个nextLine()/ nextInt()呼叫不会产生太大的影响.如果您有一个循环或者您正在阅读大量数据,那么使用readLine()with parseInt()将非常有效.
| 归档时间: |
|
| 查看次数: |
28285 次 |
| 最近记录: |