Integer.parseInt(scan.next()) 还是 scan.nextInt()?
我在使用
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();
哪个更有用或更准确的问题上摇摆不定;哪个跑得更快?
I oscillate with using
import java.util.Scanner;
.
.
.
Scanner scan = new Scanner(System.in);
.
.
.
Integer.parseInt(scan.next());
or
import java.util.Scanner;
.
.
.
Scanner scan = new Scanner(System.in);
.
.
.
scan.nextInt();
Which one is more useful, or more precisely; which would be running faster?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
现在当然,这只是 Sun 实现,但下面是 nextInt(int radix) 实现。
请注意,它使用特殊模式 (
integerPattern()
)。这意味着如果您使用next()
您将使用默认模式。现在,如果您刚刚创建了一个new Scanner()
,您将使用典型的空白模式。但如果您使用不同的模式,您就无法确定您是否能识别出某个单词。您可能正在接电话或其他什么。在一般情况下,我强烈推荐
nextInt()
,因为它为您提供了一个抽象,为您提供了更少可能出错的信息,并在出现问题时提供更多信息。闲暇时阅读以下内容:
Now granted, this is just the Sun implementation, but below is the nextInt(int radix) implementation.
Note that it uses a special pattern (
integerPattern()
). This means if you usenext()
you'll be using your default pattern. Now if you just made anew Scanner()
you'll be using a typical whitespace pattern. But if you used a different pattern, you can't be certain you'll be picking up a word. You might be picking up a line or something.In the general case I would highly recommend
nextInt()
, since it provides you with an abstraction, giving you less that's likely to go wrong, and more information when something does.Read this at your leisure:
我的直觉是 scan.nextInt、scan.next 可以读取换行符、空格或其他垃圾。可能需要更长的时间来筛选垃圾字符
My gut feeling is that scan.nextInt, a scan.next could read in newlines or whitespace or other garbage. Might take longer to sift through the junk chars
对于哪一个更快,我认为手动解析 Integer.parseInt 更快,因为 scan.nextInt 会执行基于正则表达式的匹配,然后对该值执行 Integer.parseInt
http://download.oracle.com/javase/1,5,0/docs/api/java/util/Scanner.html#nextInt()
干杯!
For which one is faster , I think manually parsing Integer.parseInt is faster, as scan.nextInt would do a regex based match and then do an Integer.parseInt on that value
http://download.oracle.com/javase/1,5,0/docs/api/java/util/Scanner.html#nextInt()
Cheers!
nextInt() 方法更方便。
应用用户验证时使用 Integer.parseInt()。
假设您希望程序将用户输入视为 5 ,并且希望在用户键入 '---5' 时显示自定义消息,其中 '--' 是空格。
在这种情况下 Integer.parseInt() 很有帮助。
nextInt() method is more handy.
Use Integer.parseInt() when you are applying user validation.
Suppose you want your program to take user input as 5 , and you want to display custom message when user types '---5' , where '--' are whitespaces.
In that case Integer.parseInt() is helpful.