Integer.parseInt(scan.next()) 还是 scan.nextInt()? [英] Integer.parseInt(scan.next()) or scan.nextInt()?

查看:65
本文介绍了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();    

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

Which one is more useful, or more precisely; which would be running faster?

推荐答案

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

Now granted, this is just the Sun implementation, but below is the nextInt(int radix) implementation.

请注意,它使用了一种特殊的模式(integerPattern()).这意味着如果您使用 next() 您将使用您的默认模式.现在,如果您刚刚创建了一个 new Scanner(),您将使用典型的空白模式.但是如果你使用了不同的模式,你就不能确定你会捡到一个词.您可能正在接电话或其他东西.

Note that it uses a special pattern (integerPattern()). This means if you use next() you'll be using your default pattern. Now if you just made a new 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.

在一般情况下,我强烈推荐 nextInt(),因为它为您提供抽象,减少出错的可能性,并在出现问题时提供更多信息.

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.

闲暇时阅读:

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

这篇关于Integer.parseInt(scan.next()) 还是 scan.nextInt()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆