简体   繁体   English

防止用户输入在2D数组中重叠-Java

[英]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? 如何防止用户在2D数组中为同一点输入两个值?

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? 例如:当在战舰游戏中使用2D阵列作为游戏板时,用户可以输入飞船起点的坐标,然后输入飞船指向的方向。显然,两艘飞船不能重叠,因此如果两艘船重叠,您将如何发送错误消息?

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 我尝试过使用for循环来遍历并找到放下新船之前已经有船的空间

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 而且我还尝试了对这两种方法进行do while循环,但是到目前为止,所有尝试都陷入了混乱,而且我几乎心脏病发作了,试图找出我做错了什么

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. 只需接受用户输入并检查该特定单元格是否为空,如下所示。如果为空且x,y是有效填充,则该单元格将显示错误消息。

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");            
        }       
    }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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