2016-04-25 112 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);