Advertisement
Guest User

Untitled

a guest
Dec 8th, 2016
68
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.23 KB | None | 0 0
  1. ```package warmup18;
  2.  
  3. import java.util.Arrays;
  4.  
  5. /**
  6. *
  7. * @author Delano
  8. */
  9. public class TicTacToe {
  10. private String[][] grid;
  11.  
  12. /**
  13. * This constructor will create a 3x3 grid for
  14. * playing TicTacToe
  15. */
  16. public TicTacToe()
  17. {
  18. grid = new String[3][3];
  19.  
  20. for (int row = 0; row < grid.length; row++)
  21. {
  22. Arrays.fill(grid[row], " ");
  23. }
  24. }
  25. public static void main(String[] args)
  26. {
  27. TicTacToe myPuzzle = new TicTacToe();
  28. myPuzzle.makeMove(1, 1, "X"); //;grid[1][1] = "X";
  29.  
  30. //this should cause an exception
  31. try{
  32. myPuzzle.makeMove(3, 2, "O");
  33. }
  34. catch (IllegalArgumentException exception)
  35. {
  36. System.out.println(exception.getMessage());
  37. }
  38. }// end of the main method
  39.  
  40. /**
  41. * This method will receive a row, a col and the player
  42. * info (X or O). It will validate if the position is
  43. * available and set the player on the position if it
  44. * is available
  45. */
  46. public void makeMove(int row, int col, String player)
  47. {
  48. if (row < 0 || row > 2)
  49. throw new IllegalArgumentException("Row must be 0-2.");
  50.  
  51. if (col < 0 || col > 2)
  52. throw new IllegalArgumentException("Column must be 0-2.");
  53.  
  54. if (grid[row][col].equals(" "))
  55. grid[row][col]=player;
  56. else
  57. throw new IllegalArgumentException("["+row+"]["+col+
  58. "] is already taken.");
  59. }
  60.  
  61. /**
  62. * This method will display the game board
  63. */
  64. public void displayGrid()
  65. {
  66. for (int row=0; row < grid.length; row ++)
  67. {
  68. for (int col=0; col < grid.length; col++)
  69. {
  70. if (col ==2)
  71. System.out.printf(" %s ", grid[row][col]);
  72. else
  73. System.out.printf(" %s |", grid[row][col]);
  74. } //end of column for loop
  75. if (row==2)
  76. System.out.println();
  77. else
  78. System.out.println("\n------------");
  79. } // end of row for loop
  80. }
  81.  
  82. }
  83. ```
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement