Letting users picking password in console is a commonly wanted feature. We let the users enter a password string, and check if it is a valid password e.g. minimal length 6 – and then asking users to confirm it again.
The following PasswordUtils provide a static method inputPasswordTwice that does the above – and return the password if password string is valid and confirmed.
package helloacm.com
import java.util.Scanner;
class PasswordUtils {
public static boolean passwordValid(String pass) {
return pass.length() >= 6;
}
public static String inputPassword() {
Scanner in = null;
String password;
var cons = System.console();
if (cons == null) {
in = new Scanner(System.in);
}
while (true) {
if (cons != null) {
var pwd = cons.readPassword("password: ");
password = String.valueOf(pwd);
} else {
var input = in.nextLine().trim();
password = input.split("\\s+")[0];
}
if (passwordValid(password)) {
return password;
}
System.out.println("Invalid password, please input again.");
}
}
public static String inputPasswordTwice() {
String password0;
while (true) {
System.out.println("Please input password.");
password0 = inputPassword();
System.out.println("Please input password again.");
var password1 = inputPassword();
if (password0.equals(password1)) {
break;
}
System.out.println("Two passwords do not match, please input again.");
}
return password0;
}
}
public class Main {
public static void main(String[] args) {
var pass = PasswordUtils.inputPasswordTwice();
System.out.println(pass);
}
}
We prefer to use the System.console.readPassword if it is available, otherwise, the Scanner with System.in is used instead.
–EOF (The Ultimate Computing & Technology Blog) —
276 wordsLast Post: Teaching Kids Programming - Max Number of Points on a Line
Next Post: Teaching Kids Programming - Convert Romans to Integers