我正在尝试编写替换这些max和min nubmers的代码然后再打印新的2d数组?
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Unesite velicinu n niza:");
int n = input.nextInt();
System.out.print("Unesite velicinu m niza:");
int m = input.nextInt();
int [][] niz = new int [n][m];
int max = niz[0][0];
for (int i =0;i<niz.length;i++){
for (int j = 0;j<niz[i].length;j++) {
niz [i][j] = (int) (Math.random()*50);
System.out.print(niz [i][j] + " ");
if (niz [i][j] > max){
max = niz [i][j];
}
}
System.out.println();
}
System.out.println("Najveci broj je: " + max);
int min = niz [0][0];
for (int i =0;i<niz.length;i++){
for (int j = 0;j<niz[i].length;j++) {
if (niz [i][j]<min){
min = niz[i][j];
}
}
}
System.out.println("Najmanji broj je: " + min);
答案 0 :(得分:0)
您可以在初始数组中确定min
和max
(我分别使用Math.min(int, int)
和Math.max(int, int)
)。像
int max = Integer.MIN_VALUE;
int min = Integer.MAX_VALUE;
int [][] niz = new int [n][m];
for (int i =0;i<niz.length;i++){
for (int j = 0;j<niz[i].length;j++) {
niz [i][j] = (int) (Math.random()*50);
System.out.print(niz [i][j] + " ");
max = Math.max(max, niz[i][j]);
min = Math.min(min, niz[i][j]);
}
System.out.println();
}
然后你可以用另一个循环交换min
和max
(和显示)。像
for (int i =0;i<niz.length;i++){
for (int j = 0;j<niz[i].length;j++) {
if (niz[i][j] == max) {
niz[i][j] = min;
} else if (niz[i][j] == min) {
niz[i][j] = max;
}
System.out.print(niz [i][j] + " ");
}
System.out.println();
}