【问题标题】:If matrix2.getElement(int y, int x) is called what do I type in the getElement method如果调用 matrix2.getElement(int y, int x) 我在 getElement 方法中键入什么
【发布时间】:2020-05-24 20:19:02
【问题描述】:

对于这个任务,我们正在编写一个不可变类,它实现了一个矩阵接口,该接口具有一些矩阵函数,加法,减法乘法......我们克隆提供的数据以创建一个不可变的新矩阵。接口中有一个 getElement(int y, int x) 方法,它返回一个 int。当提供的只是索引时,我无法弄清楚如何提取元素。我知道该方法是在一个矩阵对象上调用的,所以这就是我们从我需要的 getElement 方法中的关键字中提取的矩阵。

public class Practice {

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        Scanner in = new Scanner(System.in);
        int[][] data2 = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
        Practice m1 = new Practice(data2);

        m1.getElement(0, 1);

    }

    public Practice(int[][] matrix){
        cloneMatrix(matrix);
    }

    public static int[][] cloneMatrix(int[][] data) {

         int[][] newMatrix = new int[data.length][data[0].length];
         for (int i = 0; i < data.length; i++) {
             System.arraycopy(data[i], 0, newMatrix[i], 0, data[i].length);
         }
         return newMatrix;
    }

    public int getElement(int y, int x) {

        int !!!WHAT GOES HERE!!! [y][x];
        return j;
    }

}

【问题讨论】:

  • 要么在 Practice 类中有一个 int[][] 字段,要么将矩阵传递给方法。你不能凭空得到它:)

标签: java arrays methods get


【解决方案1】:

您需要更改一些代码才能使其正常工作:)

public class Practice {
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Scanner in = new Scanner(System.in);
        int[][] data2 = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
        Practice m1 = new Practice(data2);

        m1.getElement(0, 1);
    }

    public int[][] myMatrix; // Changed this line

    public Practice(int[][] matrix) {
        this.myMatrix = cloneMatrix(matrix); // Changed this line
    }

    public static int[][] cloneMatrix(int[][] data) {
        int[][] newMatrix = new int[data.length][data[0].length];
        for (int i = 0; i < data.length; i++) {
            System.arraycopy(data[i], 0, newMatrix[i], 0, data[i].length);
        }
        return newMatrix;
    }

    public int getElement(int y, int x) {
        return this.myMatrix[y][x]; // Changed this line
    }
}

【讨论】:

  • 哦!!!! “this”不起作用,因为我没有“this”……缺少类变量!非常感谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-12-14
  • 1970-01-01
  • 2012-05-21
  • 1970-01-01
  • 2016-02-15
  • 1970-01-01
  • 2014-07-05
相关资源
最近更新 更多