In JDK 1.5 a java.util.Scanner
class was introduced to handle user input in console application. This class enable us to read string, integer, long, etc.
package org.kodejava.util;
import java.util.Scanner;
public class ScannerDemo {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Read string input for username
System.out.print("Username: ");
String username = scanner.nextLine();
// Read string input for password
System.out.print("Password: ");
String password = scanner.nextLine();
// Read an integer input for another challenge
System.out.print("What is 2 + 2: ");
int result = scanner.nextInt();
if (username.equals("admin")
&& password.equals("secret") && result == 4) {
System.out.println("Welcome to Java Application");
} else {
System.out.println("Invalid username or password, " +
"access denied!");
}
}
}
The result of the code snippet:
Username: admin
Password: secret
What is 2 + 2: 4
Welcome to Java Application
Latest posts by Wayan (see all)
- How do I create a string of repeated characters? - September 1, 2023
- How do I convert datetime string with optional part to a date object? - August 28, 2023
- How do I split large excel file into multiple smaller files? - April 15, 2023
Good post. Explained it in an interesting way. See this as well : Taking input from user in java