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

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

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

What are the advantages as opposed to simple execution scanner.nextInt()?

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

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 can see, ScannerInteger.parseInt () also calls, in addition to additional focusing. Significant performance gains achieved simply Integer.parseInt(scanner.nextLine())? Are there any flaws, on the other hand?

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

+4
source share
3 answers

Thre - 2 observations:

  • myScannerInstance.nextInt() . , nextLine() nextInt(), nextLine() . , nextInt() nextLine(), . 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() . - (). , . nextLine() . , nextLine() 5 ( String), ( Integer.parseInt()), , int .

nextLine() + parseInt() , .

:

nextInt() , , . 123 . 123sdsa InputMismatchException. , .

nextLine() , sada1231, NumberFormatException , . .

, nextLine()/nextInt() . , readLine() parseInt() .

+7

nextInt() , . nextLine() . Java Docs:

... , . .

, , Enter, input.nextInt() , " ", , int, double .., " ", - " " . .next(), " " . , , , , . , .

0

. .

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, when it key.nextInt()leaves a new line symbol, we use key.nextLine()to transfer a new line symbol, and then move on to the next line, where the actual data is present. As we discussed above, use Integer.parseInt()will be more efficient than use nextInt(). But it is also one of the coding methods to overcome the problem.

0
source

All Articles