Java Integer.parseInt(scanner.nextLine()) 与scanner.nextInt()

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26586489/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 02:52:35  来源:igfitidea点击:

Integer.parseInt(scanner.nextLine()) vs scanner.nextInt()

javaperformanceintegerjava.util.scanneruser-input

提问by Olavi Mustanoja

My professor tends to do the following to get a number from the user:

我的教授倾向于执行以下操作以从用户那里获取数字:

Scanner scanner = new Scanner(System.in);
Integer.parseInt(scanner.nextLine());

What are the benefits as opposed to simply doing scanner.nextInt()?

与简单地做相比有什么好处scanner.nextInt()

java.util.Scanner.javahas the following in it:

java.util.Scanner.java其中包含以下内容:

public int nextInt() {
    return nextInt(defaultRadix);
}

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

As I see it, Scannercalls Integer.parseInt() itself as well, on top of additional hocus pocus. Are there significant performance gains in doing simply Integer.parseInt(scanner.nextLine())? Are there on the other hand any drawbacks?

在我看来,Scanner除了额外的 hocus pocus 之外,还会调用 Integer.parseInt() 本身。简单地做是否有显着的性能提升Integer.parseInt(scanner.nextLine())?另一方面有什么缺点吗?

How about when scanning through a file with significant amount of data, and not a user input?

当扫描具有大量数据而不是用户输入的文件时如何?

采纳答案by TheLostMind

Thre are 2 observations :

有 2 个观察:

  1. Using myScannerInstance.nextInt()leaves behind a new line character, So, if you have a call to nextLine()after nextInt(), the nextLine()will read the new line character instead of the actual data. So, you will have to add another nextLine()after the nextInt()to gobble up that danglingnew-line character. nextLine()doesn't leave behind a new line character.
  1. 使用myScannerInstance.nextInt()留下换行符,因此,如果您调用 nextLine()after nextInt()nextLine()将读取换行符而不是实际数据。所以,你得再添nextLine()nextInt()吞噬那晃来晃去的换行符。nextLine()不会留下换行符。

code :

代码 :

int age=myScannerInstance.nextInt();
String name = myScannerInstance.nextLine();// here the actual name will not be read. The new line character will be read.
  1. nextInt()will again go back to the underlying stream and read. IO calls take time (expensive). It will do lot of checks to get the next integer. nextLine()will do those checks only once.. So, if you call nextLine()once and read 5 integers (As a single line String), split them and parse them as integers (using Integer.parseInt()), it will be faster and more efficient than reading each int individually.
  1. nextInt()将再次返回底层流并读取。IO 调用需要时间(昂贵)。它将进行大量检查以获取下一个整数。nextLine()将只执行一次这些检查。因此,如果您调用nextLine()一次并读取 5 个整数(作为单行字符串),将它们拆分并将它们解析为整数(使用Integer.parseInt()),它将比单独读取每个 int 更快、更有效。

Using nextLine()+ parseInt()will give you enormous performance benefit when you are running a very large loop.

当您运行一个非常大的循环时,使用nextLine()+parseInt()将为您带来巨大的性能优势。

Usage :

用法 :

Using nextInt()gives you an additional advantage wherein you will get an exception if the input text is not an integer. example 123is accepted.. 123sdsawill throw an InputMismatchException. So, you can catch it and handle it appropriately.

使用nextInt()为您提供了一个额外的优势,如果输入文本不是整数,您将获得异常。示例123被接受..123sdsa将抛出一个InputMismatchException. 所以,你可以抓住它并适当地处理它。

Using nextLine()will read the entire line, so, it will read the entire String sada1231and then fail with NumberFormatExceptionif it cannot parse the String as a number. You will have to handle that exception.

使用nextLine()将读取整行,因此,它将读取整个字符串sada1231,然后NumberFormatException如果无法将字符串解析为数字则失败。您将不得不处理该异常。

Generally, one nextLine()/ nextInt()call won't make much of a difference. If you have a loop or if you are reading lot of data, then using readLine()with parseInt()will be very efficient.

一般来说,一个nextLine()/nextInt()电话不会有太大的不同。如果您有一个循环或者您正在读取大量数据,那么使用readLine()withparseInt()将非常有效。

回答by Payam

nextInt() reads a number, but doesn't consume line separator. While nextLine() reads the String and consumes the new-line character. According to Java Docs:

nextInt() 读取一个数字,但不消耗行分隔符。而 nextLine() 读取 String 并使用换行符。根据Java 文档

… This method returns the rest of the current line, excluding any line separator at the end. The position is set to the beginning of the next line.

… 此方法返回当前行的其余部分,不包括末尾的任何行分隔符。位置设置为下一行的开头。

In other words when you enter a number then press Enter, input.nextInt() consumes only the number, not the "end of line", primitive data types like int, double etc does not consume "end of line", due which this "end of line" remain in buffer ane When input.next() executes, it consumes the "end of line" from buffer from the first input. So you professor is trying to get to the next line after he reads the user input. You have to look at the logic of his codes only then you can understand it.

换句话说,当你输入一个数字然后按 Enter 时,input.nextInt() 只消耗数字,而不是“行尾”,像 int、double 等原始数据类型不消耗“行尾”,因此“行尾”保留在缓冲区 ane 当 input.next() 执行时,它会从第一个输入的缓冲区中消耗“行尾”。所以你的教授在阅读用户输入后试图进入下一行。你要看看他的代码逻辑,你才能理解它。

回答by Sanoaf

I also used to face this problem often. So i use to code like this..

我也经常遇到这个问题。所以我习惯这样编码..

public static void main(String[] args) {
    Scanner key= new Scanner(System.in);
    String name;
    int    age;
    age = key.nextInt();
    key.nextLine();
    name = key.nextLine();  //to carry the new line character left behind nextInt()
    System.out.println("Age : "+age);
    System.out.println("Name: "+name);
}

here as the key.nextInt()leaves a new line character we are using key.nextLine()to carry the new Line character and then move to the nextline where the actual data is present. As we discussed above using Integer.parseInt()will be more efficient than using nextInt(). But this is also one of the way to code to overcome the problem.

在这里,key.nextInt()我们使用一个新的行字符key.nextLine()来携带新的行字符,然后移动到实际数据所在的下一行。正如我们上面讨论的,使用Integer.parseInt()将比使用更有效nextInt()。但这也是克服问题的编码方法之一。