【问题标题】:How to keep a program going if a non number is typed in console如果在控制台中输入非数字,如何让程序继续运行
【发布时间】:2015-06-04 20:58:08
【问题描述】:

这是一个四人连线游戏,如果用户输入数字 1-7,则会在棋盘上放置一个圆盘。如果数字不是 1-7,则会弹出“重试”。但是,当用户输入字母或符号时,就会出现异常。 这是我的代码:

import java.util.*;
import java.awt.*;


public class ConnectFour{

   public static void main(String[] args){
      //board
      DrawingPanel panel = new DrawingPanel(550,550);
      int rowAvailable;
      Graphics g = panel.getGraphics();
      g.drawLine(0,0,0,427);
      g.drawLine(0,0,500,0);
      g.drawLine(500,0,500,427);
      g.drawLine(0,427,500,427);
      for(int i = 0; i< 6; i++){
         for(int j= 0; j<= 6; j++){
            g.setColor(Color.YELLOW);
            g.fillRect(j*71,i*71,71,71);
            g.setColor(Color.WHITE);
            g.fillOval(j*71,i*71,71,71); 
         }
      }

      //setBlankArray
      Scanner console = new Scanner(System.in);
      char[][] board = new char[6][7];
      for(int j = 0;j <= 6; j++){
         for(int i= 0; i < 6; i++){
            board[i][j] = ' ';
         }
      }
      boolean isBlack = true;
      boolean isRed = false;
      int column = 0;
      boolean playersTurn = true;
      boolean rightNum = false;

      //oneTurn
      while(getWinner(board, playersTurn)){
      //while(playersTurn == true){
         rightNum = false;
         if(isBlack == true){
            // displayCurrentPlayer
            System.out.println("Black's Turn");
            g.setColor(Color.WHITE);
            g.drawString("Red Disc's Turn",200, 450);
            g.setColor(Color.BLACK);
            g.drawString("Black Disc's Turn",200, 450);
         }
         else{
            // displayCurrentPlayer
            System.out.println("Red's Turn");
            g.setColor(Color.WHITE);
            g.drawString("Black Disc's Turn",200, 450);
            g.setColor(Color.RED);
            g.drawString("Red Disc's Turn",200, 450);
         }
         System.out.print("Choose a column to place your disk (1-7): ");
         while(rightNum == false){
            column = (console.nextInt()) -1;
            if(column >= 0 && column < 7 && board[0][column] == ' '){
               rightNum = true;
            }
            else{
               System.out.print("Try again: ");
            }
         }

         drawBoard(column, board, isBlack, isRed, board, g);
         isBlack = !isBlack;
      }
      if(isBlack == false){
         System.out.println("Congratulations Black Player");

      }
      else
         {System.out.println("Congratulations Red Player");
      }
      // use the while loop to say try again if the column is filled.
   }

   public static void drawBoard(int column, char[][] board, boolean isBlack, boolean isRed, char[][] availability,Graphics g){

      char player = ' ';
      if(isBlack == true){
         g.setColor(Color.BLACK);
         player = 'b';
      }
      else{
         g.setColor(Color.RED);
         player = 'r';
      }
      int x = 0;
      int row = 5;
      while(board[row-x][column] != ' '){
         x++;
      }
      row = row-x;
      g.fillOval((column * 71),(row * 71), 71,71);
      board[row][column] = player;
   }

   public static boolean getWinner(char[][] board, boolean playersTurn){
      int verticalCount = 0;
      boolean isVertical = false;
      for(int i = 0; i <= board[0].length - 1; i++){
         verticalCount = 0;                               
         for(int j = board.length - 1; j > 0; j--){
            if(board[j][i] == board[j-1][i] && board[j][i] != ' '){
               verticalCount++;
            } else {
               verticalCount = 0;
            }

            if(verticalCount == 3){
               isVertical = true;
            }
         }
      }

      int horizontalCount = 0;
      boolean isHorizontal = false;
      for(int i = board.length-1; i >= 0; i--){
         for(int j = 0 ; j < board[0].length-1; j++){
            if(board[i][j] == board[i][j+1] && board[i][j] != ' '){
               horizontalCount++;
            }
            else{
               verticalCount = 0;
            } 
            if(horizontalCount == 3){
               isHorizontal = true;
            }
         }
      }

      int diagonalCount = 0;
      boolean isDiagonal = false; 
     // for(int i = 0; i<=6; i++){
      //   for(int j =0; j<6; j++){
       //     if(board[i][j-1] == board[i][j]){
       //        diagonalCount++;
         //   } 
        // }
     // }

      if(isVertical || isHorizontal || isDiagonal){
         playersTurn = false;
      }
      else{
         playersTurn = true;}
      return playersTurn;
   }
}

【问题讨论】:

  • 您想要程序在输入非数字字符时抛出异常,或者它当前正在抛出异常并且您想更改它?

标签: java arrays graphics console java.util.scanner


【解决方案1】:

当您使用 console.nextInt() 时,您的代码需要一个整数

使用hasNextInt() 确定下一个内联字符是否为int,如果不是,则使用next() 跳过该字符

if(console.hasNextInt()){
     column = (console.nextInt()) -1;
     /* ... */
} else {
    console.next();
}

【讨论】:

    【解决方案2】:

    nextInt() 方法抛出:

    • InputMismatchException - 如果下一个标记与 Integer 正则表达式不匹配,或者超出范围
    • NoSuchElementException - 如果输入已用尽
    • IllegalStateException - 如果此扫描仪已关闭

    您的案例应该引发第一个异常InputMismatchException,因此您只需使用try{ catch 块:

    while(rightNum == false){
                try{
                column = (console.nextInt()) -1;
                if(column >= 0 && column < 7 && board[0][column] == ' '){
                   rightNum = true;
                 }
                }catch(InputMismatchException ime)
                {
                   //do nothing because it will achieve the else block
                }
    

    【讨论】:

    • 您应该将 if 语句移动到 try 或将 continue 添加到 catch。否则,当column 中剩下的任何内容碰到if 时,您会遇到一些错误。
    • @ChrisStillwell 他用 0 初始化了column,但无论如何你的建议更安全,谢谢。
    • 是的,但它是在循环之外初始化的,你们都没有在任何地方重置它。因此,如果您输入非法字符,您的移动将成为最后一招。
    【解决方案3】:

    您需要验证您的输入:

    // check that an int in inputted.
     if (console.hasNextInt()==true){
      // add validation for number range 
      // or some other such algorithm
        if (console.nextInt()>1= &&console.nextInt()<8){
            column = (console.nextInt()) -1;
       //etc
    

    http://docs.oracle.com/javase/6/docs/api/java/util/Scanner.html#hasNextInt%28%29

    此外,没有必要发布您的所有代码。只是相关的部分。

    【讨论】:

      猜你喜欢
      • 2022-08-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-02-01
      • 1970-01-01
      • 2013-06-30
      • 2019-11-25
      相关资源
      最近更新 更多