Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
139 views
in Technique[技术] by (71.8m points)

java - How do I compare a number in a certain index from two different 2d arrays?

So this program starts by initializing two 2d arrays that are 4 by 4. the arrays are filled with random numbers between 9 and 0. I already did those methods, and they print correctly. then, i need to compare each number in those two using enhanced for loops ONLY. whichever one is bigger will print, creating a new array. I know how to do this with regular for loops, but how would do this? hopefully this makes sense. I don't even know where to start with this, honestly.

my instance variables are:

private int[][] matrix1 = new int[4][4]; //
private int[][] matrix2 = new int[4][4];
question from:https://stackoverflow.com/questions/66058575/how-do-i-compare-a-number-in-a-certain-index-from-two-different-2d-arrays

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
public static int[][] solve(int[][] matrix1, int[][] matrix2) {
    // ignore matrix1 has same size with matrix2
    int[][] res = new int[matrix1.length][matrix1[0].length];
    
    for (int i = 0; i < matrix1.length; i++) {
        for (int j = 0; j < matrix1[0].length; j++) {
            res[i][j] = Math.max(matrix1[i][j], matrix2[i][j]);
        }
    }
    return res;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...