【发布时间】:2014-03-05 10:12:17
【问题描述】:
我真的很难找到 5x5 数组的最大和最小数字的索引,其中生成的随机数高达 1000。这是我的代码:
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 + " ");
}
}
【问题讨论】:
-
二维数组中的单个索引是什么意思?您应该同时存储
x和y。在您跟踪最大/最小值的同一if块中执行此操作是最有意义的。 -
仅供参考:您发布的代码无法编译。
标签: java arrays algorithm max min