2012-07-26 29 views
3

有沒有辦法可以退格並刪除用戶輸入的一些字母/單詞?
Java控制檯中的退格?

我正在創建一個單詞打亂遊戲,並在我做它之前,我正在做一些控制檯的東西。 由於我在第一位玩家輸入單詞時正在使用掃描儀,因此它會停留在此處。所以第二個玩家在猜詞時可以看看它。
反正有沒有從控制檯中刪除這個詞?或者讓它顯示爲* * * *?
我不希望有System.out.println("\n\n\n....");
這將使輸入顯示在底部,我希望它在頂部。 我可以刪除用戶輸入的內容嗎?或者將它顯示爲* * * * * *?
謝謝。 :)

+0

這個答案應該會幫助你:http://stackoverflow.com/a/3328871/1438307 – Benoit 2012-07-26 21:28:34

回答

1

請注意,在GUI中執行此操作實際上比使用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); 
    } 
} 

我測試過它,併爲我工作。

的更多信息:

+0

這只是打印一個* * * * * * * * *的狗屎負載......不知道我是否有問題。我只是複製你的代碼。 – 2012-07-26 21:51:21