Main Tutorials

Java Scanner examples

Long live the Scanner class, a few examples for self-reference.

1. Read Input

1.1 Read input from the console.

JavaScanner1.java

package com.mkyong.io;

import java.util.Scanner;

public class JavaScanner1 {

    public static void main(String[] args) {

        try (Scanner scanner = new Scanner(System.in)) {
            System.out.print("Please enter your name: ");
            String input = scanner.nextLine();
            System.out.println("name : " + input);

            System.out.print("Please enter your age: ");
            int age = scanner.nextInt();
            System.out.println("age : " + age);
        }
    }

}

2. Split Input

2.1 By default, the Scanner uses whitespace as delimiters to break its input into tokens.

JavaScanner2.java

package com.mkyong.markdown;

import java.util.Scanner;

public class JavaScanner2 {

    public static void main(String[] args) {

        String input = "1,2,3,4,5";
        try (Scanner s = new Scanner(input).useDelimiter(",")) {
            while (s.hasNext()) {
                System.out.println(s.next());
            }
        }

    }

}

Output


1
2
3
4
5

3. Read File

3.1 We also can use Scanner to read a file.

JavaScanner3.java

package com.mkyong.io;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class JavaScanner3 {

    public static void main(String[] args) {

        try (Scanner sc = new Scanner(new File("/home/mkyong/projects/pom.xml"))) {
            while (sc.hasNext()) {
                System.out.println(sc.nextLine());
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

    }

}

References

About Author

author image
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

Subscribe
Notify of
2 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
alex
3 years ago

Java library to scanner java class? Use burningwave.org !!

Yao Frankie
3 years ago

Thanks, you can try var, eg:

try (var sc = new Scanner(System.in)){}