方法可以返回异常吗?

时间:2016-02-10 20:27:57

标签: java methods

我真的很新java,我真的很努力地了解在Java中可以做什么,什么不可以。我正在制作一个基于众所周知的游戏Hangman的控制台应用程序。我试图做的就是阻止用户输入'e'两次以上,我做了两个方法:

每当用户键入e时,第一个将int变量 mManyTimes 加1。

  public boolean adder() {
   boolean tooMuch = letter == 'e';
   if(tooMuch) {
     mManyTimes ++;
   }
   return tooMuch;
  }

第二种方法是发送异常的方法 当用户键入e超过两次时,向用户发送。

public void cheatStopper() {
  if(mManyTimes == 3) {
   throw new IllegalArgumentException("You cant type more Es");
  }
 }

基本上我创建了两个文件,一个保存游戏代码(这两个方法都在哪个)和另一个。

保存游戏逻辑的文件是 Game.java ,这里面是代码:

public class Game {
  private String mAnswer;
  private String mHits;
  private String mMisses; 
  private int mManyTimes;
  public char letter;

  public Game(String answer) {
    mAnswer = answer;
    mHits = "";
    mMisses = "";
  }

  public boolean applyGuess(char letter) {
   //checks for char letter inside the mAnswer variable.
   //If it is there the indexOf() method should return the index of the letter.
   //If it is not  there it will return -1.
   //We are basicly saing if indexOf() method returns 0 or more then that then the isHit 
   //if it is not then the isHit boolean will return false.
   boolean isHit = mAnswer.indexOf(letter) >= 0;

   if (isHit) {
    mHits = mHits + letter;
    } else {
      mMisses = mMisses + letter;
   }
   adder();
   return isHit;


  }

  public boolean adder() {
   boolean tooMuch = letter == 'e';
   if(tooMuch) {
     mManyTimes ++;
   }
   return tooMuch;
  }

 public void cheatStopper() {
  if(mManyTimes == 3) {
   throw new IllegalArgumentException("You cant type more Es");
  }
 }

包含 main()方法并将代码打印到控制台的另一个文件是 Hangman.java

    public class Hangman {

    public static void main(String[] args) {
        // Enter amazing code here:
        Game game = new Game("treehouse");
        game.applyGuess('e');
        game.applyGuess('e');

        System.out.println(game.cheatStopper());
    }

}

所以这是让我感到沮丧的问题,我从未找到并回答: 如何让我的代码工作并阻止用户输入两个以上e。 好吧,我知道我的代码有很多错误和糟糕的结构,但不要忘记我刚接触java,并感谢提前:)。

1 个答案:

答案 0 :(得分:0)

您需要catch块。查看如何捕获异常。

相关问题