簡體   English   中英

用Java替換2D數組?

[英]Replacing in a 2D array in Java?

在此程序中,我試圖創建一個坐標平面並替換特定點的值。 如果平面中的最大值為2,則此代碼將創建一個二維數組,最大和最小值為2,並對軸進行編號,如下所示:

String [][] grid = new String [max+max+2][max+max+2];
        for (int i=0; i<max+max+1; i++)
            for (int j=0; j<max+max+2; j++)
                grid [i][j]="o";

        for (int i=0; i<max+max+1; i++)
        {Integer Col=new Integer(max-i);
        grid [i][0]=Col.toString();}

        int [] firstRow= new int [max+max+1];
        for (int i=0; i<firstRow.length; i++)
            firstRow [i]=max-max-max+i;

ex:
   -2 -1  0  1  2
 2  o  o  o  o  o
 1  o  o  o  o  o
 0  o  o  o  o  o
-1  o  o  o  o  o
-2  o  o  o  o  o

在下面的代碼中,我接收到機場的隨機x,y坐標(在此示例中,x = 1和y = -1)。 我必須在此坐標(1,-1)處將雙精度數組中的“ o”替換為“ P”。 當我嘗試執行此操作時,它將“ P”放置在正確的x坐標(1)處,而不是正確的y坐標處。 第二個for循環肯定有問題,但我不知道它是什么。 正確的替換應如下所示:

 ex:
       -2 -1  0  1  2
     2  o  o  o  o  o
     1  o  o  o  o  o
     0  o  o  o  o  o
    -1  o  o  o  P  o
    -2  o  o  o  o  o



        Integer airx = new Integer (airport1.getX());
        Integer airy= new Integer (airport1.getY());
        for (int i=0; i<firstRow.length; i++)
            if (firstRow [i]==airport1.getX())
                airx=i;

        String yCord= airy.toString();
        for (int k=0; k<grid[0].length-1; k++)
            {String w =grid [k][0];
            if (w==yCord)

        for (int i=0; i<grid[0].length-1; i++)
            if (grid [i][0]==airy.toString())
                airy=i;
        grid [airy][airx+1]="A";

如果您更改數組,則數組將更易於閱讀和建立索引

   -2 -1  0  1  2
 2  o  o  o  o  o
 1  o  o  o  o  o
 0  o  o  o  o  o
-1  o  o  o  o  o
-2  o  o  o  o  o

為此,首先更改生成和索引數組的方式

   -2 -1  0  1  2
-2  o  o  o  o  o
-1  o  o  o  o  o
 0  o  o  o  o  o
 1  o  o  o  o  o
 2  o  o  o  o  o

創建一個變量來保存數組的大小,即

int arrSize = 2*max + 2;

創建另一個變量以保存位置(0,0)的數組索引。

int arrMid = arrSize/2;

您可以使用grid [arrMid] [arrMid]訪問位置(0,0)


在您的示例中, 假設x = 1和y = -1 ,只需執行以下操作即可將該位置更新為“ P”:

Integer airx = new Integer (airport1.getX()); // 1
Integer airy= new Integer (airport1.getY());  // -1
grid[arrMid + airx][arrMid + airy] = "P";     // grid[4][2] = "P";

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM