簡體   English   中英

聲明2d變量Java

[英]declare 2d variable Java

我想知道是否可以為一個變量賦值,該變量將指向Java中2d數組中的某個確切位置。 我通過訪問數組元素

imageMatrix[width][hight].getColor1()

由於我正在考慮不同的場景,因此通過例如聲明[width] [high]會更容易。 n1=[2][1]然后打電話

imageMatrix(n1).getColor1()

它有可能嗎? 謝謝!

您可以定義一個包含二維數組單元格寬度和高度的坐標。 然后使用此類的實例到imageMatrix()方法。

就像是:

public clas Coordinate{
    private int height;
    private int width;
/*Accessors and constructors...*/


}

您可以將ImageMatrix和Point定義為類。
要設置和獲取每個點的顏色,您可以在Point類中創建方法。
在這里,我們將每個點存儲在列表中,以便將來可以訪問它們。

import java.util.ArrayList;
public class ImageMatrix {
    Point point;
    public ImageMatrix(Point point){
        this.point = point;
    }

    public static void main(String[] args) {
        //to set color and store each point into a list
        ArrayList<Point> pointList = new ArrayList<>();
        //creating 9 points with different color
        for(int i=0;i<3;i++){
            for(int j=0;j<3;j++){
                Point point = new Point(i,j);
                point.setColor("color"+i+j);
                pointList.add(point);
            }
        }
        //to get color from each point
        for(Point point : pointList){
            System.out.println("color of point " + point.height +" and " + point.width +" is : " + point.getColor());
        }
    }
}

class Point{
    public int height;
    public int width;
    public String color;

    public Point(int height, int width){
        this.height = height;
        this.width = width;
    }
    public void setColor(String color){
        this.color = color;
    }
    public String getColor(){
         return this.color;
    }
}

暫無
暫無

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

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