如何在Java中为输入显示星号?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22545603/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to display asterisk for input in Java?
提问by hacks4life
I need to write a little program in Java that asks a person to enter a Pin Code. So I need the Pin to be hidden with asterisks (*) instead of the numbers. How can I do that?
我需要用 Java 编写一个小程序,要求一个人输入 Pin 码。所以我需要用星号 (*) 而不是数字来隐藏 Pin。我怎样才能做到这一点?
So far, this is my code :
到目前为止,这是我的代码:
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);
}
}
Actually this program works for now, but I want to add a functionality to display Pin like "* * * " or "* *" etc... (in the console when the Person enters is own Pin). I found something to entirely hide the Pin, but I do not want this. I want the Pin with asterisks
实际上这个程序现在可以工作,但我想添加一个功能来显示像“* * * ”或“* *”等的Pin......(当Person进入时在控制台中是自己的Pin)。我找到了完全隐藏 Pin 的东西,但我不想要这个。我想要带星号的 Pin 图
Any ideas ? Thanks
有任何想法吗 ?谢谢
采纳答案by elias
Something like this:
像这样的东西:
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("0*");
try {
Thread.currentThread().sleep(1);
} catch(InterruptedException ie) {
ie.printStackTrace();
}
}
}
public void stopMasking() {
this.stop = true;
}
}
回答by erickson
The Console
class is the correct way to read passwords from the command line. However, it doesn't print asterisks, as that would leak information in general (not in the case where a PIN is known to be 4 digits). For something like that, you'd might need a curses library.
该Console
班是读取命令行密码的正确方法。但是,它不打印星号,因为这通常会泄漏信息(在已知 PIN 为 4 位数字的情况下不会)。对于这样的事情,您可能需要一个 curses 库。