战舰游戏 - 例外

时间:2016-04-25 19:55:11

标签: java

我正在为一个赋值做一个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);

3 个答案:

答案 0 :(得分:1)

假设您的其余代码有效,您只需更改var elt = document.getElementById("#your-element-id"); elt.style.setProperty("-webkit-filter", "drop-shadow(5px 5px 5px #222)"); 语句即可确保条目有效。

使用OR运算符if

||

答案 1 :(得分: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);

答案 2 :(得分:0)

根据我的经验,更好的方法是创建自己的例外

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

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

makeGuess抛出BadMoveException,然后对于用户可以进行的任何无效移动,你可以用它创建一个BadMoveException,并将它打印在makeGuess之外的catch {}块中

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