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

我的教授倾向于做以下事情来从用户那里得到一个数字:

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

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

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

正如我所看到的, Scanner在其他hocus pocus之上调用Integer.parseInt()本身。 只做Integer.parseInt(scanner.nextLine())会有显着的性能提升吗? 另一方面有任何缺点吗?

扫描具有大量数据的文件而不是用户输入时怎么样?

有2个观察结果:

  1. 使用myScannerInstance.nextInt()留下一个换行符,因此,如果在nextInt()之后调用nextLine() nextInt() ,则nextLine()将读取换行符而不是实际数据。 所以,你必须在nextInt()之后添加另一个nextLine() nextInt()来吞噬那个悬空的换行符。 nextLine()不会留下新的行字符。

代码:

 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()将再次返回底层流并读取。 IO调用需要时间(昂贵)。 它将进行大量检查以获得下一个整数。 nextLine()只执行一次这样的检查。所以,如果你调用nextLine()一次并读取5个整数(作为单行String),拆分它们并将它们解析为整数(使用Integer.parseInt() ),它将比单独读取每个int更快更有效。

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

用法:

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

使用nextLine()将读取整行,因此,它将读取整个String sada1231 ,如果无法将String解析为数字,则会失败并返回NumberFormatException 。 您将不得不处理该exception。

通常,一个nextLine() / nextInt()调用不会产生太大的影响。 如果你有一个循环或者你正在阅读大量数据,那么使用带有parseInt() readLine() parseInt()将非常有效。

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

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

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

我也常常经常面对这个问题。 所以我用这样的代码..

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

这里key.nextInt()留下一个新的行字符,我们使用key.nextLine()来携带新的Line字符,然后移动到存在实际数据的nextline。 正如我们上面讨论的那样,使用Integer.parseInt()将比使用nextInt()更有效。 但这也是解决问题的代码之一。