我摇摆不定地使用
import java.util.Scanner;
.
.
.
Scanner scan = new Scanner(System.in);
.
.
.
Integer.parseInt(scan.next());或
import java.util.Scanner;
.
.
.
Scanner scan = new Scanner(System.in);
.
.
.
scan.nextInt(); 哪个更有用,或者更准确;哪个运行得更快?
发布于 2011-11-08 05:35:54
现在,这只是Sun实现,但下面是nextInt(整数基数)实现。
注意,它使用了一种特殊的模式(integerPattern())。这意味着如果你使用next(),你将使用你的默认模式。现在,如果您刚刚创建了一个new Scanner(),那么您将使用一个典型的空白模式。但如果你使用了不同的模式,你就不能确定你是否会选择一个单词。你可能会拿起一句台词或者别的什么。
在一般情况下,我强烈推荐nextInt(),因为它为您提供了一种抽象,为您提供了更少的可能出错的信息,并在出现错误时提供了更多的信息。
在你空闲的时候阅读这篇文章:
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());
}
}发布于 2011-11-08 05:35:59
我的直觉是scan.nextInt,一个scan.next可以读入换行符、空格或其他垃圾。可能需要更长的时间来筛选垃圾字符
发布于 2011-11-08 05:41:58
对于哪个更快,我认为手动解析Integer.parseInt更快,因为scan.nextInt将执行基于正则表达式的匹配,然后对该值执行Integer.parseInt
http://download.oracle.com/javase/1,5,0/docs/api/java/util/Scanner.html#nextInt()
干杯!
https://stackoverflow.com/questions/8042833
复制相似问题