3

ユーザーが入力した文字や単語をバックスペースして削除する方法はありますか?

私はワード スクランブラー ゲームを作成していますが、GUI にする前に、いくつかのコンソール操作を行っています。最初のプレイヤーが単語を入力したときにスキャナーを使用しているので、そこにとどまります。そのため、2 番目のプレーヤーはスクランブルされた単語を推測するときにそれを見ることができます。
コンソールからその単語を削除する方法はありますか? それとも * * * * のように表示しますか? 入力が下部に表示され、上部に表示されるようにし
たくないのです。System.out.println("\n\n\n....");
ユーザーが入力したものを削除したり、* * * * * * のように表示したりできますか?
ありがとう。:)

4

1 に答える 1

1

GUI でこれを行うことは、実際にはScannerIMOP で行うよりもはるかに簡単であることに注意してください。

これを行う 1 つの方法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);
   }
}

私はそれをテストし、私のために働いています。

詳しくは:

于 2012-07-26T21:28:08.827 に答える