【问题标题】:declare 2d variable Java声明二维变量 Java
【发布时间】:2016-05-18 11:01:57
【问题描述】:

我想知道是否可以将一个值分配给一个指向 Java 二维数组中某个确切位置的变量。 我正在通过

访问数组元素
imageMatrix[width][hight].getColor1()

并且由于我正在考虑不同的场景,因此通过例如声明 [width][high] 会更容易。 n1=[2][1] 然后调用

imageMatrix(n1).getColor1()

有可能吗?谢谢!

【问题讨论】:

  • imageMatrix[widht][height].getColor1()不是一个方法,而是一个数组元素的访问,在访问的数组元素上调用cetColor1()。你可以定义一个方法imageMatrix(...),带有一些拟合类型的参数(例如Pair<Integer, Integer>或一些自写的类)。
  • 使用 OOP。编写将包含 x 和 y 的类 - 点 f.e。然后你可以编写接收 Point 对象的方法。
  • 简而言之,@Turing85 正在逃避。没有。

标签: java arrays variables assign


【解决方案1】:

您可以定义一个包含二维数组单元格的宽度和高度的类 Coordinate。然后将此类的实例用于您的 imageMatrix() 方法。

类似:

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


}

【讨论】:

  • 谢谢,但我仍然明显遗漏了一些东西。如果我定义 public void Point(int width, int height) { this.width=width; this.height=height;} 然后使用 Point n1= new Point(3,3); 尝试调用 imageMatrix(n1).getColor1() 我仍然收到错误“方法 imageMatrix(Point) 未定义为图片类型”
【解决方案2】:

您可以将 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;
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-02-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多