Site icon

Read contents from console or command line (Scanner/ Java/ Example)

1. Class hierarchy of Scanner class:

Fig: Scanner class hierarchy

2. Read contents from console/command line in java (scanner/example)

package org.learn.io.scan;

import java.io.IOException;
import java.util.Scanner;

public class ReadConsoleUsingScanner {

    public static void main(String[] args) throws IOException {
        System.out.println("Enter value on console:");
        try (Scanner scanner = new Scanner(System.in)) {
            while (scanner.hasNext()) {
                if (scanner.hasNextInt()) {
                    System.out.println("Integer value from console : " + scanner.nextInt());
                } else if (scanner.hasNextDouble()) {
                    System.out.println("Double value from console : " + scanner.nextDouble());
                } else if (scanner.hasNext()) {
                    String input = scanner.next();
                    if (input.equals("complete")) {
                        System.out.println("Successfully read contents from console");
                        //Successfully read input from console
                        break;
                    } else {
                        System.out.println("String value from console : " + input);
                    }
                }
            }
        }
    }
}

3. OP: read contents from console/command line (java/scanner/example)

Enter value on console:
25
Integer value from console : 25
63.24
Double value from console : 63.24
ConsoleReader
String value from console : ConsoleReader
complete
Successfully read contents from console
Exit mobile version