Integer.parseInt(scan.next()) or scan.nextInt()?

浪子不回头ぞ 提交于 2019-12-11 04:46:53

问题


I oscillate with using

import java.util.Scanner;
.
.
.
Scanner scan = new Scanner(System.in);
.
.
. 
Integer.parseInt(scan.next());

or

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?


回答1:


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

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.

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.

Read this at your leisure:

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:


My gut feeling is that scan.nextInt, a scan.next could read in newlines or whitespace or other garbage. Might take longer to sift through the junk chars




回答3:


For which one is faster , I think manually parsing Integer.parseInt is faster, as scan.nextInt would do a regex based match and then do an Integer.parseInt on that value

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

Cheers!




回答4:


nextInt() method is more handy.

Use Integer.parseInt() when you are applying user validation.

Suppose you want your program to take user input as 5 , and you want to display custom message when user types '---5' , where '--' are whitespaces. In that case Integer.parseInt() is helpful.



来源:https://stackoverflow.com/questions/8042833/integer-parseintscan-next-or-scan-nextint

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!