0

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.

4
  • 3
    Why are you passing/expecting indexes as doubles? They should be int. Commented Mar 18, 2019 at 17:33
  • 3
    The indices of an array are integers, not doubles. Use the appropriate type. Commented Mar 18, 2019 at 17:34
  • You should never use doubles as indexes for arrays, pass in integers instead. You can't access position [0.5]. The compiler is likely complaining because it needs to convert them to integers in order to use them as the index. Commented Mar 18, 2019 at 17:34
  • As an aside: follow naming conventions: the method should be named getElement, and the matrix should be named a (or, even better, a more descriptive name) Commented Mar 18, 2019 at 17:41

1 Answer 1

3

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];
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.