更新时间:2023-02-26 16:33:31
您应该跟踪的两个 X
和是
最大/最小元素的索引。无需后期处理,这簿记只是一个问题:
如果(MAX<数字[X] [Y]){
最大=数字[X] [Y]
MAXX = X;
MAXY = Y;
}
I'm really stumped trying to find the index of the largest and smallest numbers of a 5x5 array with random numbers up to 1000 generated into them. Here my code:
import java.util.Random;
public class MaxMinArray {
public static void main (String args[]) {
int x=0, y=0, max=0, min=1000;;
int[][] numbers = new int[5][5];
for (x=0; x<numbers.length; x++) { //outer for
for(y=0; y<numbers.length; y++) { //inner for
numbers[x][y]= (int)(Math.random()*1000); //random generator
if(max < numbers[x][y]) //max number
max = numbers[x][y];
if(min>numbers[x][y]) //min number
min = numbers[x][y];
int maxIndex = 0;
for(int index = 1; index<numbers.length; index++)
if(numbers[maxIndex]< numbers[index])
maxIndex = index;
}
}
System.out.println("Max number in array:" + max + " ");
System.out.println("Max number is in" + maxIndex + " ");
System.out.println("Min number in array:" + min + " ");
}
}
You should keep track of both the x
and y
index of the maximum/minimum element. No need to post-process, it's just a matter of bookkeeping:
if(max < numbers[x][y]) {
max = numbers[x][y];
maxX = x;
maxY = y;
}