简体   繁体   中英

preventing overlap of user input in a 2D array - java

How would one prevent the user from entering two values for the same spot in a 2D array?

For example: when given a 2D array as the playing board in a game of battleship, the user can input the coordinates of the start of the ship, and then the direction that the ship points in. Obviously two ships can't overlap, so how would you send an error message if two ships overlapped?

I've tried two methods: I've tried counting up the empty spaces in the array, but I have no way of making a method to check then new coordinates (it goes on into infinity)

I've tried using a for loop to run through and find the spaces where there is already a ship before placing down a new ship

And I've also tried do while loops for both of these methods in main, but so far all attempts have fallen into chaos and I've nearly had a heart attack trying to figure out what I'm doing wrong

Sorry if there's some easy solution I'm not seeing. It's late

Thanks

Simply take the user input and check if that particular cell is null or not as follows.If it is null and x, y is valid fill that cell else show error message.

public class Cell {
    int x;
    int y;

    public Cell(int x, int y){
        this.x = x;
        this.y = y;
    }
    public static void main(String args[]){
        Cell board[][] = new Cell[5][5];//We have 5*5 board, so total 25 cells
        Scanner sc= new Scanner(System.in);
        for(int i=0;i<25;i++){
            int x= sc.nextInt();
            int y = sc.nextInt();
            if(x<5 && y< 5 && board[x][y] == null)
                {
                    Cell cell = new Cell(x, y);
                    board[x][y] = cell;

                }
            else
                System.out.println("Invalid Input");            
        }       
    }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM