2016-04-25 107 views
0

我正在爲一個任務做一個java程序,其中一個例外是用戶不能輸入一個不存在的行或列的值。即,如果電路板是5x7並且用戶輸入了值爲10的列,則屏幕將打印「錯誤:無效列」。然而,我不確定如何做這個最後的例外,我需要今天提交它。如果有人可以幫助,我會非常感激!這裏是我的makeGuess()函數代碼:戰列艦遊戲例外

public void makeGuess(){ 
     //guesses is for keeping track of your guesses 
     boolean cont=true; 
     int rowGuess; 
     int columnGuess; 
     do{ 
     System.out.println("Enter a row to guess >"); 
     rowGuess = (input.nextInt()-1); 
     if(rowGuess<=0){ 
      System.out.println("You did not enter a positive Integer.Please try again"); 
     cont=false;} 
     else{ 
     cont=true;} 
     } 
     while (cont==false); 


     do{ 
      System.out.println("Enter a column to guess >"); 
      columnGuess = (input.nextInt()-1); 
      if(columnGuess <=0){ 
       System.out.println("You did not enter a positive integer.Please try again"); 
       cont=false; 
      } else{ 
       cont=true; 
      } 
     }while(cont==false); 

回答

0

一種更好的方式在我的經驗,這樣做是爲了創造自己的異常

public class BadMoveException extends Exception { 
    BadMoveException(Exception ex) { 
    super(ex); 
    } 

    BadMoveException(String ex) { 
    super(ex); 
    } 
} 

makeGuess拋BadMoveException,然後對任何的無效的移動用戶可以進行,您可以創建一個BadMoveException,並在catch {}塊打印makeGuess

while (!gameOver) { 
    try { 
    makeGuess(); 
    } 
    catch (BadMoveException ex) { 
    System.out.println("You tried to make an invalid move:" + ex.getMessage()); 
    } 
} 
1

之外假設日剩下的代碼可以工作,你可以簡單地修改你的if語句以確保輸入有效。

使用OR運算符||

if (columnGuess <= 0 || columnGuess >= 10){ 
    System.out.println("Error: invalid Column"); 
} 
1

就像你有一個if語句來測試,如果數量太少,你還需要測試它是否太大

public void makeGuess(){ 
    //guesses is for keeping track of your guesses 
    boolean cont=true; 
    int rowGuess; 
    int columnGuess; 
    do{ 
     System.out.println("Enter a row to guess >"); 
     rowGuess = (input.nextInt()-1); 
     if(rowGuess<=0){ 
      System.out.println("You did not enter a positive Integer.Please try again"); 
      cont=false; 
     }else if(rowGuess>7){ 
      System.out.println("You did not enter a small enough Integer.Please try again"); 
      cont=false; 
     }else{ 
      cont=true; 
     } 
    }while (cont==false); 


    do{ 
     System.out.println("Enter a column to guess >"); 
     columnGuess = (input.nextInt()-1); 
     if(columnGuess <=0){ 
      System.out.println("You did not enter a positive integer.Pleasetry again"); 
      cont=false; 
     }else if(columnGuess>5){ 
      System.out.println("You did not enter a small enough Integer.Please try again"); 
      cont=false; 
     } else{ 
      cont=true; 
     } 
    }while(cont==false);