【问题标题】:Java: How to stop console input from typing a certain characterJava:如何阻止控制台输入输入某个字符
【发布时间】:2015-01-27 06:49:28
【问题描述】:

我正在制作一个刽子手程序,我想为字母/字母/符号提供大量布尔值,他们会做的是,当它们为真时,我希望控制台禁止输入字符。

例如:我输入了 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”这个东西,我不担心程序不工作,因为这是只是“示例”代码,它不是为了工作 - 而是为了说明问题。所以你不必在代码的外观上批评我,因为在网站上制作“代码”斑点是相当困难的,所以我真的不想让它变得非常详细。

【问题讨论】:

  • 当您说要存储“大量布尔值”时,我认为这是在数组中 (boolean letters[] = new boolean[26])?
  • 嗯,目前我对数组一无所知,所以,不,我只是想要一个相当长的列表,比如 boolean a, b, c, d, e ... a=false; b=false;c=false 等

标签: java console boolean


【解决方案1】:

我建议如下:

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.
  }
}

虽然这是一个完整的类,但它本身并不会真正做任何有用的事情,因为其中没有实际的游戏逻辑。

【讨论】:

  • 全是红色 :o prntscr.com/5xvtm4 我对你放在那里的任何东西都不是很熟悉(大多数数组就像不同的语言)我不知道我是否必须拥有任何包含在顶部,我总是把 include java.util.* 因为我将它用于扫描仪,所以我不知道我需要放什么让它不红色:l 另外,从我“做”的样子来看关于编码,它似乎只是要输入字符,但是当您按 Enter 时它可能不会显示?我不知道太复杂了,我无法理解,因为它代表 xD
猜你喜欢
  • 2016-03-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-01-25
相关资源
最近更新 更多