Simple practice with Scanner in Java

What is the result of the following program?

import java.util.Scanner;
public class Looking {
    public static void main(String[] args){
        String input = "1 2 a 3 45 6";
        Scanner sc = new Scanner(input);
        int x = 0;
        do{
            x = sc.nextInt();
            System.out.print(x + " ");
        }while(x != 0);
    }
}

The following is the result:

run:
Exception in thread "main" java.util.InputMismatchException
        at java.util.Scanner.throwFor(Scanner.java:840)
        at java.util.Scanner.next(Scanner.java:1461)
        at java.util.Scanner.nextInt(Scanner.java:2091)
        at java.util.Scanner.nextInt(Scanner.java:2050)
        at Looking.main(Looking.java:19)
1 2 Java Result: 1
BUILD SUCCESSFUL (total time: 0 seconds)

The nextXxx() methods are typically invoked after a call to a hasNextXxx(), which determines whether the next token is of the correct type. Here there is no such method, so an exception is thrown.(java.util.InputMismatchException)

The following is the corrected code:

public class Looking {
    public static void main(String[] args){
        String input = "1 2 a 3 45 6";
        Scanner sc = new Scanner(input);
        int x = 0;
        while(sc.hasNextInt()){
            x = sc.nextInt();
            System.out.print(x + " ");
        }
    }
}

The result is:

run:
1 2 BUILD SUCCESSFUL (total time: 0 seconds)

Leave a Comment