2017-04-20 8 views
-1

これは簡単かつ迅速に答えるべきです。それは例外を投げることに関するもので、私はその話題についてはほとんど理解していません(私は初心者なので)。おそらく、例外をスローすることに関する非常に単純な答えるクエリ

以下のコードは、私の単純な「迷路ゲーム」プログラムの最も重要なメソッドを表しています。このメソッドでは、可能なユーザーのキーボードコマンドを列挙し、他のサブメソッドを呼び出すことによって実行の指示を与えています(明らかに)。明らかに、私は、 "ヘルプ"、 "ステータス" ... "ダウン"ではないすべてのキーボード入力がメソッドの最後にエラーメッセージを表示したい。

ここで私が知っていることはダムではありませんが、例外ではありませんが、それは例外を投げることについて私が何をしているのかが文字通り知られていないためです。 。だから誰かが私がここに書きたいものを書く方法を教えてもらえるのであれば、私は大好きです。他

public static void performAction(String action) throws IllegalArgumentException { 
    if (action.equalsIgnoreCase("help")) { 
     printHelp(); } 
    else if (action.equalsIgnoreCase("status")) { 
     printStatus(); } 
    else if (action.equalsIgnoreCase("board")) { 
     printBoard(); } 
    else if (((action.charAt(0) == 'S') || (action.charAt(0) == 's')) && ((action.charAt(1) == 'a') || (action.charAt(1) == 'A')) && ((action.charAt(2) == 'v') || (action.charAt(2) == 'V')) && 
    ((action.charAt(3) == 'e') || (action.charAt(3) == 'E')) && (action.charAt(4) == ' ')) { 
     String [] parts = action.split(" "); 
     String saveCommand = parts[0]; 
     String fileName = parts[1]; 
     try { saveGame(fileName); } 
     catch(IOException e) { 
      System.err.printf("Error: Could not save the current game configuration to \'%s\'.", fileName); 
      return; } } 
    else if (action.equalsIgnoreCase("left")) { 
     int a = getCurrentXPosition(); 
     int b = getCurrentYPosition(); 
     moveTo((a - 1), b); } 
    else if (action.equalsIgnoreCase("right")) { 
     int a = getCurrentXPosition(); 
     int b = getCurrentYPosition(); 
     moveTo((a + 1), b); } 
    else if (action.equalsIgnoreCase("up")) { 
     int a = getCurrentXPosition(); 
     int b = getCurrentYPosition(); 
     moveTo(a, (b - 1)); } 
    else if (action.equalsIgnoreCase("down")) { 
     int a = getCurrentXPosition(); 
     int b = getCurrentYPosition(); 
     moveTo(a, (b + 1)); } 
    else { 
     try {} 
    catch (IllegalArgumentException e) { 
     System.err.printf("Error: Could not find command \'%s\'.\nTo find the list of valid commands, please type 'help'. \n", action); } 
    } 
    } 
+1

はIllegalArgumentException例外をスローすることによってメソッドを終了します ''他 – SomeJavaGuy

+0

これはどのようにあなたの前の質問に違うのですか? http://stackoverflow.com/questions/43513726/how-to-limit-the-string-arguments-that-a-method-can-use-to-a-fixed-list –

+0

エラーを印刷したいだけならメッセージでは、例外をスローする必要はありません。 'else'ブロックにエラーメッセージを表示するだけです。 – khelwood

答えて

0

{ System.err.printf( "エラー:コマンドが見つかりませんでした\ '%sの\' \ NTOは、[ヘルプ]を入力してください\ nは、有効なコマンドのリストを見つける"、アクション);

throw IllegalArgumentException; }} 新しいはIllegalArgumentException(yourMessageを)投げる{これは、メッセージをログに記録し、その後

関連する問題