0
\$\begingroup\$

My homework asks me to define a 2d array and find the max value, and the min value in the index of the max value here's how I did it

public class Main {
public static void main(String[] args) {
int[][] ar = {{11,12,9,14,60},{200,50,23,19,25},{31,100,33,34,35}};
int max = ar[0][0];
int y = 0;
for (int i = 0; i <ar.length;i++){
 for (int k=0;k < ar[i].length;k++){
 if (ar[i][k] > max) {
 max = ar[i][k];
 y = i;
 }
 }
}
int minInMaxLine = ar[y][0];
for (int i =0;i<ar[y].length;i++){
 if (ar[y][i] < minInMaxLine){
 minInMaxLine = ar[y][i];
 }
}
System.out.println("Max value is : "+max);
System.out.println("Index of max value is : "+y);
System.out.println("Min value in max value's index is : "+minInMaxLine);
 }
}

this outputs :

Max value is : 200

Index of max value is : 1

Min value in max value's index is : 19

Raystafarian
7,2991 gold badge23 silver badges60 bronze badges
asked Mar 22, 2018 at 5:41
\$\endgroup\$

2 Answers 2

1
\$\begingroup\$

This approach looked great I think you should try to consider more cases then the ones you added in your example your algorithm should consider cases as if the 2d array was null as well. For reference please click here.

Isac
5744 silver badges12 bronze badges
answered Mar 22, 2018 at 6:08
\$\endgroup\$
0
\$\begingroup\$

I don't think it can get much simpler or more straightforward than your code. One way to improve upon what you already have is to also handle the case that the maximum value occurs more than once. True, the exercise does not prescribe how to deal with this situation, but it's something you might want to consider.

You could also choose a more meaningful variable name for y, like you did with the other variables.

answered Mar 23, 2018 at 8:31
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.