2016-02-18 66 views
0

我的問題是我不知道如何從同一個掃描器行(用空格分隔)讀取兩個整數,並驗證它們是否都是整數,如果不是,則打印相應的錯誤消息並重新提示。這是一些如何打印錯誤消息兩次當我輸入兩個非整數作爲輸入TicTacToe遊戲驗證問題的兩個整數在同一個掃描器行

/** 
* Gets the position from the user of where the next move should be   
* made. The board is then updated with a valid move 
* 
* @return true if there is a winner and false if there is no winner 
* 
*/ 



public boolean getMove() 
{ 


boolean invalid = true; 
int row = 0; 
int column = 0; 

//keeps asking for a position until the user enters a valid one 
while (invalid) 
{ 

    row = -1; 
    column = -1; 

    System.out.println("Which row, column would you like to move to? Enter two numbers between 0-2 separated by a space to indicate position in (x,y)."); 

    if (keyboard.hasNextInt()) 
    { 

     row = keyboard.nextInt(); 

     if (keyboard.hasNextInt()) 
     { 

      column = keyboard.nextInt(); 

     } 
    } else 
    { 

     keyboard.nextLine(); 
     System.out.println("\nBoth inputs must be integers between 0 and 2.\n"); 

    } 
    //check that the position is within bounds 
    if (row >= 0 && row <= 2 && column >= 0 && column <= 2) 
    { 

     //check that the position is not already occupied 
     if (board[row][column] != ' ') 
     { 
      System.out.println("That position is already taken"); 
     } else 
     { 
      invalid = false; 
     } 
    } else 
    { 
     System.out.println("Invalid position"); 
    } 
} 

//if it's currently X's turn then mark the space as char 'X' else 'O' 
if (xTurn) 
{ 
    board[row][column] = 'X'; 

} else 
{ 
    board[row][column] = 'O'; 

} 

//fill in the game board with the valid position 
return winner(row, column); 

}

回答

0

可以讀取它作爲一個字符串,用空格分開,讓每個條目的值。