In Java, you can read different data types using the Scanner class with specific methods for each type. Here are examples for reading int, double, and String:
import java.util.Scanner;
public class ReadDifferentDataTypes {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Read an integer
System.out.print("Enter an integer: ");
int number = scanner.nextInt();
// Read a double
System.out.print("Enter a decimal number: ");
double decimal = scanner.nextDouble();
// Read a string
scanner.nextLine(); // Consume the newline left-over
System.out.print("Enter your name: ");
String name = scanner.nextLine();
// Display the inputs
System.out.println("Integer: " + number);
System.out.println("Decimal: " + decimal);
System.out.println("Name: " + name);
scanner.close();
}
}
Explanation:
scanner.nextInt();reads an integer value.scanner.nextDouble();reads a double (decimal) value.scanner.nextLine();reads a line of text (string). Note that we callscanner.nextLine();after reading a number to consume the leftover newline character.
This way, you can read various data types from user input in Java. Let me know if you need further assistance!
