Reading Different Types of Input from Keyboard in Java
In Java, we use the Scanner
class to read different types of input from the keyboard, such as integers, doubles, strings, and characters. Below are examples demonstrating how to use Scanner
to read these data types.
Java में हम कीबोर्ड से विभिन्न प्रकार के इनपुट पढ़ने के लिए Scanner
क्लास का उपयोग करते हैं, जैसे कि int, double, string, और char। नीचे कुछ उदाहरण दिए गए हैं जो दिखाते हैं कि Scanner कैसे काम करता है।
Example 1: Read Integer Input
import java.util.Scanner;
public class ReadInteger {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter an integer: ");
int num = sc.nextInt();
System.out.println("You entered: " + num);
sc.close();
}
}
Output:
Enter an integer: 25 You entered: 25
Reads an integer value from the user and prints it.
यूजर से integer इनपुट पढ़ता है और उसे प्रिंट करता है।
Example 2: Read Double Input
import java.util.Scanner;
public class ReadDouble {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a double value: ");
double val = sc.nextDouble();
System.out.println("You entered: " + val);
sc.close();
}
}
Output:
Enter a double value: 12.34 You entered: 12.34
Reads a double (decimal) value from the user and prints it.
यूजर से double (दशमलव) इनपुट पढ़ता है और उसे प्रिंट करता है।
Example 3: Read String Input
import java.util.Scanner;
public class ReadString {
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();
}
}
Output:
Enter your name: Astha Hello, Astha!
Reads a full line string input from the user and prints a greeting.
यूजर से पूरा स्ट्रिंग इनपुट पढ़ता है और एक अभिवादन प्रिंट करता है।
Example 4: Read Character Input
import java.util.Scanner;
public class ReadChar {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a character: ");
char ch = sc.next().charAt(0);
System.out.println("You entered: " + ch);
sc.close();
}
}
Output:
Enter a character: A You entered: A
Reads a single character from user input and prints it.
यूजर से एक अक्षर पढ़ता है और उसे प्रिंट करता है।