【问题标题】:Accept only a letter input只接受字母输入
【发布时间】:2013-12-07 06:01:23
【问题描述】:

我正在处理我的刽子手程序的错误。如果用户输入数字(int/double)而不是字母(char/string),我想打印一条错误消息。我该怎么做?

这是引擎类的代码:

//hangman viewer stuff
//////////////////////////////////////////////////////////////
JFrame frame = new JFrame();

frame.setSize(200,375); //invoked the method setSize on the implicit parameter frame
frame.setTitle("Hangman"); 
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

HangmanComponent g = new HangmanComponent();
frame.add(g);

frame.setVisible(true);

///////////////////////////////////////////////////////////////

String wordd = JOptionPane.showInputDialog("Type in a word.");
int length = wordd.length();
String blank = "_ ";
String word2 = new String("");
int guesscount = 10;

ArrayList<String>answers=new ArrayList<String>(); //creates reference to empty structure that will contain references
char blanks[]=new char[wordd.length()]; //creates an array with the same number of terms as the length of the word
for (int i=0; i<length; i++)//fills the array with blanks corresponding to the length of the word
{
    blanks[i] = '_';
}

HangmanComponent y = new HangmanComponent();

while (true)
{
    String letter = JOptionPane.showInputDialog("Guess a letter! You have "+guesscount+" guesses."+"\n"+answers+"\n"+Arrays.toString(blanks).replace(",", " ").replace("[","").replace("]","")); //Prints a space
    char letterchar = letter.charAt(0); //converts string letter to char letterchar
    int idx = 0;
    boolean found = false;
    answers.add(letter); //adds the string to the arraylist answers

    while (idx >= 0 && idx < length) //idx is greater than or equal to 0 but less than the length of the word
    {
        //System.out.println("idx = " + idx);
        idx = wordd.indexOf(letter, idx); //idx is the index of "letter" in "wordd" and finds all instances of the letter
        //System.out.println("idx = " + idx + ", guesscount = " + guesscount);
        if (idx != -1) //if idx is not -1 (the letter exists in the word)
        {
            found = true;
            blanks[idx] = letterchar; //sets the term in the array equal to the letter 
            idx += 1; //idx=idx+1
        } 
        else 
        {
            guesscount=guesscount-1;
            y.nextStage();
            y.printStage();
            frame.add(y);
            frame.setVisible(true);
            break;
        }
    }

    if (found)
    {
        JOptionPane.showMessageDialog(null, Arrays.toString(blanks).replace(",", " ").replace("[","").replace("]","")+"\n"+"You found a letter!"+"\n"+answers);
    }
    else 
    {
        JOptionPane.showMessageDialog(null, Arrays.toString(blanks).replace(",", " ").replace("[","").replace("]","")+"\n"+"That letter is not in the word! Guess again!"+"\n"+answers);

        if (guesscount == 0)
        {
            JOptionPane.showMessageDialog(null, "Sorry, you're all out of guesses. The answer was '"+wordd+".' Thanks for playing!");
            break;
        }
    }

    char [] lettersArray = wordd.toCharArray(); //converts word to array of chars

    if (Arrays.equals(blanks, lettersArray))//compares array of blanks to array of letters
    {
        JOptionPane.showMessageDialog(null, "You guessed the word! Thanks for playing!");
        break;
    }
}

}

【问题讨论】:

  • 好奇这都是写在main函数里的吗?
  • 您可以创建一个可接受的字符数组,以及一个对其进行排序并检查变量(无论输入是什么)是否等于其中任何一个的方法;如果不是,则抛出错误并停止程序或再次向他们询问正确的字符(据说使用 while 循环)。这就是我的做法,尽管我只使用 Ruby 做过,从未在 Java 中尝试过。自动检查可能有很多更好的方法,但我不知道。
  • @theGreenCabbage 是的,这一切都在主函数中
  • 作为为我的 Java 初学者课程完成这个项目的人,你真的应该学习面向对象编程。它让生活变得如此轻松。
  • 一些“A3”允许吗?

标签: java error-handling


【解决方案1】:

尝试,使用正则表达式检查单词是否仅包含字母。

 String wordd = JOptionPane.showInputDialog("Type in a word.");
 if(!wordd.matches("[a-zA-Z]+")){
   // Invalid word.
 }

【讨论】:

    【解决方案2】:

    你也可以使用正则表达式:

      if(str.matches(".*\\d.*")){
        // contains a number
      } else{
       // does not contain a number
      }
    

    【讨论】:

      【解决方案3】:

      只需简单地接受用户的输入然后

      试试这个。

      try{
          Integer.parseInt(yourInput);
           //error message
      }catch(Exception e){
          //output
      } 
      

      【讨论】:

      • 其实错误信息应该在try而不是catch中。这是因为如果它是一个数字,op 希望它出错消息。
      猜你喜欢
      • 1970-01-01
      • 2023-01-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-04-13
      • 2011-04-17
      • 2014-03-26
      • 2020-12-25
      相关资源
      最近更新 更多