【问题标题】:Backspacing in Java Console?Java控制台中的退格?
【发布时间】:2025-12-18 04:00:01
【问题描述】:

有没有一种方法可以退格并删除用户输入的一些字母/单词?

我正在创建一个单词扰码器游戏,在我制作它的 GUI 之前,我正在做一些控制台的东西。 因为当第一个玩家输入一个单词时我使用的是扫描仪,所以它会停留在那里。所以第二个玩家在猜测打乱的单词时可以只看它。
无论如何要从控制台中删除该词?或者让它显示为 * * * *?
我宁愿没有System.out.println("\n\n\n....");
这将使输入出现在底部,我希望它出现在顶部。 我可以删除用户输入的内容或使其显示为 * * * * * * 吗?
谢谢。 :)

【问题讨论】:

标签: java console passwords java.util.scanner privacy


【解决方案1】:

请注意,在 GUI 中执行此操作实际上比使用Scanner IMOP 更容易。

使用Scanner 执行此操作的一种方法是创建一个线程,在输入字符时擦除它们并用 * 替换它们

EraserThread.java

import java.io.*;

class EraserThread implements Runnable {
   private boolean stop;

   /**
    *@param The prompt displayed to the user
    */
   public EraserThread(String prompt) {
       System.out.print(prompt);
   }

   /**
    * Begin masking...display asterisks (*)
    */
   public void run () {
      stop = true;
      while (stop) {
         System.out.print("\010*");
     try {
        Thread.currentThread().sleep(1);
         } catch(InterruptedException ie) {
            ie.printStackTrace();
         }
      }
   }

   /**
    * Instruct the thread to stop masking
    */
   public void stopMasking() {
      this.stop = false;
   }
}

passwordfield.java

public class PasswordField {

   /**
    *@param prompt The prompt to display to the user
    *@return The password as entered by the user
    */
   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();
      }
      // stop masking
      et.stopMasking();
      // return the password entered by the user
      return password;
   }
}

主要方法

class TestApp {
   public static void main(String argv[]) {
      String password = PasswordField.readPassword("Enter password: ");
      System.out.println("The password entered is: "+password);
   }
}

我已经对其进行了测试,并且正在为我工​​作。

更多信息:

【讨论】: