If you have any query feel free to chat us!
Happy Coding! Happy Learning!
In Java, you can read input from the user through the standard input stream using the java.util.Scanner
class or the older java.io.BufferedReader
class. These classes allow you to capture input from the user, making your Java programs interactive and dynamic.
Here's an example of reading user input using java.util.Scanner
:
javaCopy code
import java.util.Scanner;
public class UserInputExample {
public static void main(String[] args) {
// Create a Scanner object to read input from the standard input stream (System.in)
Scanner scanner = new Scanner(System.in);
System.out.print("Enter your name: ");
String name = scanner.nextLine(); // Read the entire line of input as a string
System.out.print("Enter your age: ");
int age = scanner.nextInt(); // Read an integer input
// Display the user's input
System.out.println("Hello, " + name + "! You are " + age + " years old.");
// Remember to close the Scanner object to release resources
scanner.close();
}
}
In this example, we use the Scanner
class to read user input. The Scanner
object is created with System.in
as the argument, which represents the standard input stream (usually the keyboard). The nextLine()
method reads the entire line of input as a string, and the nextInt()
method reads an integer input.
It's important to note that nextInt()
and other methods for reading specific data types do not consume the newline character (Enter key) from the input buffer. If you plan to read additional input after using such methods, you may need to consume the newline character separately using scanner.nextLine()
before reading the next line of input.
Remember to close the Scanner
object using the close()
method when you're done with it to release the resources associated with it.
Similarly, you can use java.io.BufferedReader
to read user input:
javaCopy code
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class UserInputExample {
public static void main(String[] args) throws IOException {
// Create a BufferedReader object to read input from the standard input stream (System.in)
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter your name: ");
String name = reader.readLine(); // Read the entire line of input as a string
System.out.print("Enter your age: ");
int age = Integer.parseInt(reader.readLine()); // Read a line of input and parse it to an integer
// Display the user's input
System.out.println("Hello, " + name + "! You are " + age + " years old.");
// Remember to close the BufferedReader object to release resources
reader.close();
}
}
Both approaches allow you to interact with the user and capture input dynamically, making your Java programs more versatile and interactive.
Comments: 0