I have a project for my computer science class, and we are doing the battleship. Part of the program is that we make sure that the part that the player puts does not go overboard.
I made a way to check if it comes out of the board:
private static boolean test(String s, int row, int column,int spaces) { if(s.equals("right")&&column+5<=10) { return true; } if(s.equals("up")&&row-spaces>=0) { return true; } if(s.equals("left")&&column-spaces>=0) { return true; } if(s.equals("Down")&&row+spaces<=10) { return true; } return false; }
But as soon as I got a printout of the error message, I'm not sure how to do this so that the program can re-get the new position for the part without putting the if statement in the if statement in the if statement (and so on), because you need to check the new position to make sure it doesnโt go out of the board.
Here is the part where I get the position of the play (although I donโt think you need it)
Scanner sonic= new Scanner(System.in); System.out.println("Please input the row where you want the aircraft carrier (5 spaces) to begin: "); int beginrow = sonic.nextInt(); System.out.println("Please input the column where you want the aircraft carrier (5 spaces) to begin: "); int begincolumn = sonic.nextInt(); System.out.print("Please input what direction (up, down, left, right) \nyou want your battle ship to face, making sure it doesn't go off of the board."); String direction = sonic.next();
And here is one of the if statements I use to check / place fragments
if(direction.equals("left")&&test("left",beginrow,begincolumn,5)) { for(int i = beginrow; i>beginrow-5; i--) { battleship[begincolumn-1][i-1] = ('a'); } } else if(!test("left",beginrow,begincolumn,5)) { System.out.println(" "); System.out.println("*****ERROR: your piece goes off the board, please re-enter your position and direction*****"); }
It may be a duplicate, but I did not know how to change my search to find what I wanted. (So, if someone could direct me to the right article, that would be nice)