Java:如何阻止控制台输入键入某个字符

时间:2015-01-27 06:49:29

标签: java console boolean

我正在制作一个刽子手程序,我想要有大量的字母/字母/符号布尔,他们会做的是,当它们是真的时,我希望控制台不要打字那个字符。

例如:我输入了g作为字符,然后按Enter键。我的程序现在有g = true布尔值。我需要system.forceConsole.input.stop(forLetter:g)或类似的爵士乐,所以它甚至不能再次在控制台中输入g。

我只想知道这是否可以远程实现,如果是......我可以看一个剪切/粘贴示例,看看它是否是我正在寻找的?

下面只是我想到的一个小例子代码,这绝不会真正起作用,但它应该表明我想要的......

      input = new Scanner(System.in);
      boolean a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z;
      //set all listed booleans to false
      char userCharacter;


      System.out.print("Please enter a letter");
      userCharacter=input.nextChar();
      if (userCharacter==letterArray){//That would be an array to get the letters 
                                      //Still don't know how to use them
      if (letterArray == true)
      {System.deny.Console.input(forChar:letterArray)}
      }

我正在考虑的最重要的事情是试图查看它是否存在于其他系统代码中是“System.deny.Console.input”的事情,我并不担心程序无法正常工作,因为这是只是“示例”代码不是为了工作 - 而是为了得到一个观点。因此,您不必在代码看起来的方式上批评我,因为在网站上制作“代码”斑点是相当困难的,所以我真的不想让它真正详尽。

1 个答案:

答案 0 :(得分:0)

我建议如下:

public class Hangman {
  boolean usedLetters[] = new boolean[26];
  boolean gameOver = true;

  String inputString = "";
  char testLetter = 0;

  public static void main(String[] args) {
    // Initialize each boolean in the array to 'false'.
    Arrays.fill(usedLetters, false);

    System.out.println("Try a letter by typing it and pressing enter");
    System.out.println("(additional letters will be ignored, lower case only)");


    while (!gameOver) {
      // Get the characters entered on the console before enter is pressed
      inputString = System.console.readLine();

      // Get the first letter entered and adjust the value so that a = 0, b = 1, etc...
      testLetter = inputString.toCharArray()[0] - 'a';

      // Check to see if the letter is valid
      if (testLetter <= 25 && testLetter >= 0) {
        // Check if letter has beed tried before
        if (!usedLetters[testLetter]) {
          // Do something to check the letter
          tryLetter(testLetter);
          // Remember that the letter has been tried
          usedLetters[testLetter] = true;
        } else {
          // Do nothing
        }
      }
    }
  }

  public static tryLetter(char letter) {
    // Insert your code to update the display here.
    // Remember to set 'gameOver' to 'true' when you want to stop accepting input.
  }
}

虽然这是一个完整的课程,但它本身并没有真正做任何有用的事情,因为那里没有实际的游戏逻辑。