【问题标题】:Integer.parseInt(scan.next()) or scan.nextInt()?Integer.parseInt(scan.next()) 还是 scan.nextInt()?
【发布时间】:2011-12-23 23:27:36
【问题描述】:

我在使用中摇摆不定

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

哪个更有用,或更准确;哪个会跑得更快?

【问题讨论】:

  • @AlexanderPogrebnyak A java.util.Scanner.
  • @Josh。我向您的读心能力(以及 Java 库的知识)鞠躬 :)
  • 对不起,我刚刚更正了

标签: java performance parseint


【解决方案1】:

现在承认,这只是 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());
    }
}

【讨论】:

    【解决方案2】:

    我的直觉是 scan.nextInt,scan.next 可以读取换行符、空格或其他垃圾。筛选垃圾字符可能需要更长的时间

    【讨论】:

      【解决方案3】:

      对于哪个更快,我认为手动解析 Integer.parseInt 更快,因为 scan.nextInt 会进行基于正则表达式的匹配,然后对该值执行 Integer.parseInt

      http://download.oracle.com/javase/1,5,0/docs/api/java/util/Scanner.html#nextInt()

      干杯!

      【讨论】:

        【解决方案4】:

        nextInt() 方法更方便。

        在应用用户验证时使用 Integer.parseInt()。

        假设您希望您的程序将用户输入视为 5 ,并且您希望在用户键入 '---5' 时显示自定义消息,其中 '--' 是空格。 在这种情况下, Integer.parseInt() 很有帮助。

        【讨论】:

          猜你喜欢
          • 2012-12-05
          • 2017-08-10
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2010-11-27
          相关资源
          最近更新 更多