java - 获取和设置方法不更改数组

标签 java arrays class

我扩展了一个类,希望通过使用 set1sub(sub.local) 方法来存储全局数组(使类内的数组可以被另一个对象看到)

public class BattleShipsClient extends ShipLocations implements Runnable, BattleShipConstants
{

BattleShipsClient()
{ 
}

public void placeBoard(int player) throws IOException// this is only called once and not updated when clicked again 
{
    while(getLocations())

    {
        while(isWaiting())//true
        {
            toServer.writeInt(player);
    int row = getRowSelected();
    int col = getColumnSelected();
    int choice=Integer.parseInt(JOptionPane.showInputDialog("Please 1 for a sub, 2 for a battleship and 3 for a destroyer"));
    clickCount ++;

    if(clickCount >2)
    {
        setLocation(false);
        continueToPlay=true;
    }

    if (choice ==1 &&sub.placed==false)
    {
        String orientation =JOptionPane.showInputDialog("please enter your orientations");


        if(orientation.equalsIgnoreCase("h"))
        {


            //row os the same
            //column number will be sent, then plus one on the other side
            sub.local = new int[2][2];
            sub.local[0][0] =row;
            sub.local[0][1]=col;
            sub.local[1][0]=row;
            sub.local[1][1] =col+1;

            toServer.writeInt(row);
            toServer.writeInt(col);


            toServer.writeChar('s');


            sub.placed=true;
            setp1sub(sub.local);
                          /*setp1sub(new int[][]{{row,col},
                    {row,col+1}});*/


            grid[row][col+1].setToken(getMyToken());

        }

然后我有一个船舶位置类,但是当我创建船舶位置类的新对象并尝试读取该数组时,它始终设置为 [[0, 0], [0, 0]],我尝试制作它是静态的和原子的

public class ShipLocations {


int [][] p1sub;

public ShipLocations()
{
    p1sub = new int[2][2];
}
public int[][] getp1sub()
{
    return p1sub;
}
public void setp1sub(int[][] local) {
    for (int i = 0;i <local.length;i++)
    {
        for(int j = 0;j<local.length;j++)
        {
            p1sub [i][j]= local[i][j];
        }
    }

}



}

最佳答案

每当您创建 ShipLocations(或子类)的新实例时,都会调用构造函数,在您的情况下,它将重新初始化 p1sub 数组。

在您的设计中,您过度使用了继承。您不应该仅仅为了使用类的方法和变量而继承类。

在类中存储全局变量:

public class ShipLocations {
 static int [][] p1sub;
 static{
  p1sub = new int[2][2];
 }
 public static void setp1sub(...){...}
 public static int[][] getp1sub(){...}
}

然后通过类名使用它而不是创建实例:

int [][] x = ShipLocations.getp1sub();

尽管应尽可能避免使用全局变量。它被认为是糟糕的设计,并且在重用代码时可能会出现问题。 正确的方法是将 ShipLocations 对象作为 BattleShipsClient 中的本地变量,并在初始化新实例时设置它。然后,您将首先创建一个通用的 ShipLocation 对象,并将其交给应该看到相同数组的每个客户端。

关于java - 获取和设置方法不更改数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14334589/

相关文章:

java - 试图了解如何将变量插入 jdbc sql 查询中?

android - 将 byteArray 转换为 android 中的位图?

java - Java中各种输入的函数的内存

C++类编译

java - 声明一个全局变量,或者在每个类中声明多次

java - 从 double 到 int 的可能有损转换?

java - Android Studio - 获取数字而不是 HTML 内容

ruby-on-rails - 将嵌套数组的字符串表示形式转换为数组

c++ - 无法访问类中声明的私有(private)成员

java - 将所有输入转换为大写