Get specific element from array in Java

旧巷老猫 提交于 2020-03-05 04:59:59

问题


Basically I am trying to return an element from an 2d array in java. I have created a separate Matrix class and inside the class I want to write a get_element method which would take as input the coordinates of the element I want from the matrix and the matrix itself, however I am not sure how to do this.

public static double get_element(Matrix A, double m , double n)
{  
    for(int i=0;i<A.rows;i++)
        for(int j=0;j<A.cols;j++)
           return A.data[m][n];


}

This is how my code look right now. And I get an error that says lossy conversion between double and int.


回答1:


You don't need the loop. Also, you need to convert the double to int

return A.data[(int) m][(int) n];

Alternatively (better), you change the method signature:

public static double get_element(Matrix A, int m , int n) {  
    return A.data[m][n];
}


来源:https://stackoverflow.com/questions/55226963/get-specific-element-from-array-in-java

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!