简体   繁体   English

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

[英]Integer.parseInt(scanner.nextLine()) vs scanner.nextInt()

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.java has 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, Scanner calls Integer.parseInt() itself as well, on top of additional hocus pocus.正如我所看到的, Scanner本身也会调用 Integer.parseInt(),这是在额外的 hocus pocus 之上。 Are there significant performance gains in doing simply Integer.parseInt(scanner.nextLine()) ?简单地执行Integer.parseInt(scanner.nextLine())是否有显着的性能提升? Are there on the other hand any drawbacks?另一方面有什么缺点吗?

How about when scanning through a file with significant amount of data, and not a user input?扫描包含大量数据而不是用户输入的文件时怎么样?

There are 2 observations :有2个观察:

  1. Using myScannerInstance.nextInt() leaves behind a new line character.使用myScannerInstance.nextInt()留下一个换行符。 So, if you call nextLine() after nextInt() , the nextLine() will read the new line character instead of the actual data.因此,如果您在nextInt() nextLine()之后调用nextLine() ,则nextLine()将读取换行符而不是实际数据。 Consequently, you will have to add another nextLine() after the nextInt() to gobble up that dangling new-line character.因此,您必须在nextInt()之后添加另一个nextLine() nextInt()以吞噬那个悬空的换行符。 nextLine() doesn't leave behind a new line character. 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. nextInt()将再次返回底层流并读取。 IO calls take time (expensive). IO 调用需要时间(昂贵)。 It will do lot of checks to get the next integer.它将进行大量检查以获取下一个整数。 nextLine() will do those checks only once. nextLine()只会做一次这些检查。 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.因此,如果您调用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.使用nextInt()给你一个额外的好处,如果输入文本不是整数,你会得到一个异常。 example 123 is accepted.. 123sdsa will throw an InputMismatchException .例如123被接受.. 123sdsa将抛出InputMismatchException So, you can catch it and handle it appropriately.所以,你可以抓住它并适当地处理它。

Using nextLine() will read the entire line, so, it will read the entire String sada1231 and then fail with NumberFormatException if it cannot parse the String as a number.使用nextLine()将读取整行,因此,它将读取整个 String sada1231 ,然后如果它无法将 String 解析为数字,则会以NumberFormatException失败。 You will have to handle that exception.您将不得不处理该异常。

Generally, one nextLine() / nextInt() call won't make much of a difference.通常,一个nextLine() / nextInt()调用不会有太大的不同。 If you have a loop or if you are reading lot of data, then using readLine() with parseInt() will be very efficient.如果您有一个循环或者您正在读取大量数据,那么将readLine()parseInt()将非常有效。

nextInt() reads a number, but doesn't consume line separator. nextInt() 读取一个数字,但不消耗行分隔符。 While nextLine() reads the String and consumes the new-line character.而 nextLine() 读取 String 并使用换行符。 According to Java Docs :根据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.换句话说,当你输入一个数字然后按 Enter 时,input.nextInt() 只消耗数字,而不是“行尾”,像 int、double 等原始数据类型不消耗“行尾”,因此“行尾”保留在缓冲区 ane 当 input.next() 执行时,它会从第一个输入的缓冲区中消耗“行尾”。 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.你要看看他的代码逻辑,你才能理解它。

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.在这里,当key.nextInt()留下一个新行字符时,我们使用key.nextLine()来携带新的 Line 字符,然后移动到实际数据所在的下一行。 As we discussed above using Integer.parseInt() will be more efficient than using nextInt() .正如我们上面讨论的,使用Integer.parseInt()将比使用nextInt()更有效。 But this is also one of the way to code to overcome the problem.但这也是克服问题的编码方法之一。

nextInt() leaves behind a new line character. nextInt()留下一个换行符。 So, if you call nextLine() after nextInt() , the nextLine() will read the new line character instead of the actual data.因此,如果您在nextInt() nextLine() ) , nextLine()将读取换行符而不是实际数据。 Consequently, you will have to add another nextLine() after the nextInt() to gobble up that dangling new-line character.因此,您将不得不在nextInt() nextLine() ) 以吞噬那个悬空的换行符。

public class Solution {

    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        int i = scan.nextInt();
        double d = scan.nextDouble();
        scan.nextLine();
        String s = scan.nextLine();
    
        scan.close();


        System.out.println("String: " + s);
        System.out.println("Double: " + d);
        System.out.println("Int: " + i);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM