Implementing Keyboard Input and Random Number Generation in Java
Handling Keyboard Input with Scanner
To capture different data types from keyboard input in Java, use the Scanner class following these steps:
- Import the Scanner class:
import java.util.Scanner; - Create a Scanner object:
Scanner input = new Scanner(System.in); - Use appropriate methods to read differnet data types:
input.next()for Stringinput.nextInt()for integerinput.nextDouble()for doubleinput.nextBoolean()for boolean
- Close the scanner:
input.close();
Example Implementation:
import java.util.Scanner;
public class UserInputExample {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Welcome to our registration system!");
System.out.print("Enter username: ");
String username = input.next();
System.out.print("Enter age: ");
int age = input.nextInt();
System.out.print("Enter weight: ");
double weight = input.nextDouble();
System.out.print("Are you single (true/false): ");
boolean isSingle = input.nextBoolean();
System.out.print("Enter gender (M/F): ");
char gender = input.next().charAt(0);
System.out.println("\nRegistration details:");
System.out.println("Username: " + username);
System.out.println("Age: " + age);
System.out.println("Weight: " + weight);
System.out.println("Single: " + isSingle);
System.out.println("Gender: " + gender);
input.close();
}
}
Ganerating Random Numbers
To generate random numbers within a specific range:
- Use
Math.random()wich returns a double between 0.0 (inclusive) and 1.0 (exclusive) - For a range [a, b], use:
(int)(Math.random() * (b - a + 1)) + a
Example Implementation:
public class RandomNumberGenerator {
public static void main(String[] args) {
// Generate random number between 1 and 6
int diceRoll = (int)(Math.random() * 6) + 1;
System.out.println("Dice roll: " + diceRoll);
// Generate random number between 10 and 20
int randomInRange = (int)(Math.random() * 11) + 10;
System.out.println("Random between 10-20: " + randomInRange);
}
}