gpt4 book ai didi

java - Integer.parseInt(scan.next()) 还是 scan.nextInt()?

转载 作者:行者123 更新时间:2023-11-29 06:07:40 26 4
gpt4 key购买 nike

我在使用中 Swing 不定

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();

哪个更有用,或者更准确地说;哪个运行得更快?

最佳答案

现在承认,这只是 Sun 的实现,但下面是 nextInt(int radix) 的实现。

请注意,它使用了一种特殊模式 (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());
}
}

关于java - Integer.parseInt(scan.next()) 还是 scan.nextInt()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8042833/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com