我需要用 Java 编写一个小程序,要求用户输入 Pin 码。 因此,我需要用星号 (*) 而不是数字来隐藏 Pin 图。我怎样才能做到这一点?
到目前为止,这是我的代码:
import java.util.Scanner;
import java.io.*;
public class codePin {
public static void main(String[] args){
int pinSize = 0;
do{
Scanner pin = new Scanner(System.in);
System.out.println("Enter Pin: ");
int str = pin.nextInt();
String s = new Integer(str).toString();
pinSize = s.length();
if(pinSize != 4){
System.out.println("Your pin must be 4 integers");
} else {
System.out.println("We're checking if Pin was right...");
}
}while(pinSize != 4);
}
}
实际上这个程序现在可以工作,但我想添加一个功能来显示 Pin 图,例如“* * * ”或“ * *”等...(当人员输入时在控制台中)是自己的 Pin)。 我找到了一些可以完全隐藏 Pin 图的东西,但我不想要这个。我想要带星号的 Pin 图
有什么想法吗?谢谢
最佳答案
类似这样的事情:
import java.io.*;
public class Test {
public static void main(final String[] args) {
String password = PasswordField.readPassword("Enter password:");
System.out.println("Password entered was:" + password);
}
}
class PasswordField {
public static String readPassword (String prompt) {
EraserThread et = new EraserThread(prompt);
Thread mask = new Thread(et);
mask.start();
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String password = "";
try {
password = in.readLine();
} catch (IOException ioe) {
ioe.printStackTrace();
}
et.stopMasking();
return password;
}
}
class EraserThread implements Runnable {
private boolean stop;
public EraserThread(String prompt) {
System.out.print(prompt);
}
public void run () {
while (!stop){
System.out.print("\010*");
try {
Thread.currentThread().sleep(1);
} catch(InterruptedException ie) {
ie.printStackTrace();
}
}
}
public void stopMasking() {
this.stop = true;
}
}
关于java - 如何在Java中显示输入的星号?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22545603/