2016-02-10 68 views
0

那麼我真的很新的Java和即時通訊真的很難明白什麼可以在Java中做什麼,什麼不能。我正在製作基於知名遊戲Hangman的控制檯應用程序。 Basiclay我試圖做的是停止用戶鍵入'e的兩次以上,這樣做我做了2種方法:方法可以返回異常嗎?

第一個增加1到int變量mManyTimes每當用戶輸入e。

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"); 
    } 
} 

Basicly我創建了兩個文件,一個保存遊戲(這這兩種方法都)和另一個的代碼。

保持所述遊戲的邏輯是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"); 
    } 
} 

另一個文件代碼到控制檯是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()); 
    } 

} 

因此,這裏是我感到沮喪的問題,我從來沒有發現和回答: 如何讓我的代碼正常工作,並停止用戶輸入更多然後兩個電子郵件。 嗯,我知道我的代碼有很多錯誤和糟糕的結構,但不要忘了即時通訊新的Java,並感謝提前:)。

+1

您的標題和您的帖子提出兩個不同的問題。至於你的標題:是的方法可以返回異常。畢竟,例外是對象。 –

+0

'return'和'throw'是兩個不同的概念,恰好恰好是Java中的關鍵字 –

+0

你可能已經得到了這個谷歌搜索「如何處理異常Java」,順便說一句。 – djechlin

回答

0

您需要一個catch塊。查找如何捕獲異常。