Input console using java

www.lau‮‬tturi.com
Input console using java

To input from the console in Java, you can use the Scanner class or the BufferedReader class.

Here is an example of how to use the Scanner class to input from the console:

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter your name: ");
        String name = sc.nextLine();
        System.out.println("Hello, " + name + "!");
        sc.close();
    }
}

In this example, the Scanner class is used to read a line of input from the console. The nextLine() method is used to read the line as a String, and the String is then printed to the console.

Here is an example of how to use the BufferedReader class to input from the console:

import java.io.BufferedReader;
import java.io.InputStreamReader;

public class Main {
    public static void main(String[] args) throws Exception {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        System.out.print("Enter your name: ");
        String name = br.readLine();
        System.out.println("Hello, " + name + "!");
        br.close();
    }
}

In this example, the BufferedReader class is used to read a line of input from the console. The readLine() method is used to read the line as a String, and the String is then printed to the console.

For more information on the Scanner class and the BufferedReader class in Java, you can refer to the Java documentation and the Java tutorial.

Created Time:2017-11-01 22:29:44  Author:lautturi