Artur Malka :
I have a problem with my program. I want to print min and max in each column but It doesn't work properly. I think everything should be ok. When the loop comes to end I restart min and max value.
public class tablice2 {
public static void main(String[] args){
int t [][] = new int [5][5];
int n [] = new int [5];
int x [] = new int [5];
Random r = new Random();
int min = t[0][0];
int max = t[0][0];
for (int i = 0; i <t.length ;i++){
min = 0;
max = 0;
for(int j = 0; j < t[i].length ;j++){
t[i][j] = r.nextInt(6)-5;
System.out.print(t[i][j] + " ");
if (t[j][i] < min){
min = t[j][i];
}
if (t[j][i] > max){
max = t[j][i];
}
}
n[i]=min;
x[i]=max;
System.out.println(" ");
}
for(int p=0;p<x.length;p++){
System.out.println("Max Column "+p + ": " +x[p] );
}
for(int k=0;k<n.length;k++){
System.out.println("Min Column "+k + ": " +n[k]);
}
}
}
Arvind Kumar Avinash :
Do not input and sort at the same time as the elements may still be initialized with the default values (i.e 0
). Also, in the outer loop, reset max
and min
to the first element of the column.
Do it as follows:
import java.util.Random;
public class Main {
public static void main(String[] args) {
int t[][] = new int[5][5];
int n[] = new int[5];
int x[] = new int[5];
Random r = new Random();
int min;
int max;
for (int i = 0; i < t.length; i++) {
for (int j = 0; j < t[i].length; j++) {
t[i][j] = r.nextInt(10) - 5;
System.out.printf("%4d", t[i][j]);
}
System.out.println();
}
for (int i = 0; i < t.length; i++) {
min = t[0][i];
max = t[0][i];
for (int j = 0; j < t[i].length; j++) {
if (t[j][i] < min) {
min = t[j][i];
}
if (t[j][i] > max) {
max = t[j][i];
}
}
n[i] = min;
x[i] = max;
}
for (int p = 0; p < x.length; p++) {
System.out.println("Max Column " + p + ": " + x[p]);
}
for (int k = 0; k < n.length; k++) {
System.out.println("Min Column " + k + ": " + n[k]);
}
}
}
A sample run:
3 -4 2 0 1
-2 -2 4 -1 -2
-3 1 4 -1 0
-4 4 -2 -5 2
-5 -3 -3 -4 -1
Max Column 0: 3
Max Column 1: 4
Max Column 2: 4
Max Column 3: 0
Max Column 4: 2
Min Column 0: -5
Min Column 1: -4
Min Column 2: -3
Min Column 3: -5
Min Column 4: -2
Notes:
- I have changed
r.nextInt(6)-5
tor.nextInt(10) - 5
in order to produce a mix of negative, 0 and positive numbers so that you can quickly validate the result. You can change it back tor.nextInt(6)-5
as per your requirement. - I have also used
printf
instead ofprint
to print each number with a space of 4 units. You can change it back toprint
if you wish so. - Use of
Integer.MAX_VALUE
and/orInteger.MIN_VALUE
is not required at all to solve this problem.
Feel free to comment in case of any doubt.