Java Scanner

Posted in /  

Java Scanner
ramyashankar

Ramya Shankar
Last updated on March 19, 2024

    Java Scanner class is used to obtain input from the user. It is the best way for the program to read interactive command-line input. Java Scanner inputs the data from the user and processes it accordingly. The class is available from Java version 5 onwards.

    Java user input and scanner class

    In Java, user input can be obtained using the System.in, taken as a parameter by the Scanner class. The Scanner class can parse primitive data types and Strings, using regular expressions, and break the input into tokens using a delimiter (for example, whitespace, tab, comma, etc.).

    Java Scanner example

    Here we present a simple Java Scanner example and discuss common exceptions. We will also learn how to use a delimiter to separate data of different types.

    Scanner scanner = new Scanner(System.in);
    System.out.println("Enter you name:");
    String name = scanner.next();
    System.out.println("Enter your gender:");
    char gender = scanner.next().charAt(0);
    System.out.println("Enter age:");
    int age = scanner.nextInt();
    System.out.println(String.format("Welcome %s, you entered your gender as %s and age as %d!", name, gender, age));

    Note that we store the gender as a character, so even if the user inputs the full gender, the program takes only the first character. Also, for integers, we are using the nextInt method. If there is a mismatch in the input, the program will throw an exception. In the above case, we have not handled the following exception: Exception in thread "main" java.util.InputMismatchException This can occur when the scanner expects input as int, but you give a string or any other data type. To try this, you can type some letters for the age. Since we are getting input from users, it is very likely that they type some wrong inputs, and hence we should handle this error through a try/catch so that the program exits gracefully. Let us see a program to split the data using a pattern:

    System.out.println("Enter few numbers separated by spaces: ");
    String pattern = "[0-9]*";
    while(scanner.hasNext())
    System.out.println("Number: " + scanner.next(pattern));

    Again in the above, we need to catch the InputMismatchException, which will be thrown if the pattern is incorrect. It is important to close the scanner in the end of the program:

    scanner.close();

    Conclusion

    In this article, we have shown how to use Scanner for user inputs. Though there are many ways in which Scanner class can be used, including passing a string as Scanner scanner = new Scanner("1 2 3 4 5 6 7 8"); or a file location to read from the file contents, we have shown examples only for how the scanner is used for Java user inputs.

    People are also reading:

    Leave a Comment on this Post

    0 Comments