本文介绍了如何在Java中显示星号以进行输入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要用Java编写一个小程序,要求一个人输入Pin Code.因此,我需要使用星号(*)而不是数字来隐藏图钉.我该怎么办?

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?

到目前为止,这是我的代码:

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);
    }
}

实际上该程序现在可以使用,但是我想添加一个功能来显示Pin,例如"* * * "或" * *"等(在人员"输入时在控制台中是自己的Pin).我发现了一些东西可以完全隐藏大头针,但我不希望这样.我想要带星号的图钉

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

有什么想法吗?谢谢

推荐答案

类似以下内容:

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中显示星号以进行输入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-02 08:04