Java readLine: Usage & Code Example
In Java, you can use the readLine() method of the BufferedReader class to read user input data. The readLine() method is used to read a line of text from the console and return it as a string. Here is a simple example:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
public class Main {
public static void main(String[] args) {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
try {
System.out.print("Enter your name: ");
String name = reader.readLine();
System.out.println("Hello, " + name + "!");
} catch (IOException e) {
System.err.println("Error reading input");
e.printStackTrace();
}
}
}
In the example above, we start by creating a BufferedReader object to read user input. We then use the readLine() method to read the input name and store it in a variable. Finally, we print a simple greeting message that includes the user’s input name.
Please note that the readLine() method may throw an IOException, so it is necessary to use a try-catch block to handle the exception.