How to get the user input in Java?
To get user input in Java, you can use the Scanner
class. Here's an example of how to get a string input from the user:
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a string: ");
String inputString = scanner.nextLine();
To get an integer input, you can use the nextInt
method like this:
Scanner scanner = new Scanner(System.in);
System.out.print("Enter an integer: ");
int inputInt = scanner.nextInt();
To get a double input, you can use the nextDouble
method like this:
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a double: ");
double inputDouble = scanner.nextDouble();
You can also use the nextBoolean
method to get a boolean input, and the next
method to get a token (a series of characters separated by whitespace).
Remember to close the scanner when you are done with it to free up system resources:
scanner.close();