G
G
gn_vadim2021-10-23 16:46:23
Java
gn_vadim, 2021-10-23 16:46:23

Why is it impossible to find the minimum non-zero number in an array?

You need to find the minimum non-zero number in the array. In the if, I write that the number !=0, but as a result it still displays 0. What's the problem?

public class Main {
    public static void main(String[] args) {
        int[][] arr = new int[][]{
                {0, 2, 0, 0, 8},
                {2, 0, 7, 0, 4},
                {0, 7, 0, 3, 5},
                {0, 0, 3, 0, 6},
                {8, 4, 5, 6, 0}};

        int Min = arr[0][0];
        for (int i = 0; i < 5; i++){
            for (int j = 0; j < 5; j++) {
                if ((arr[i][j] != 0) && (arr[i][j] < Min)  ) Min = arr[i][j];
            }}
        System.out.println(Min);
    }
}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
R
Rsa97, 2021-10-23
@Rsa97

int Min = arr[0][0];
You have arr[0][0] == 0, so this is the minimum value.
Use Integer.MAX_VALUE

A
Artem, 2021-10-23
@Trame2771

Just put a check for assigning Min (in general, such variables are written with a small letter)
For example:

int min;
int nextI, nextJ
for (int i = 0; i < 5; i++){
  for (int j = 0; j < 5; j++) {
    if (arr[i][j] != 0) min = arr[i][j];
    nextI = i;
    nextJ = j;
  }
}
if (nextI == 4) {
  nextI = 0;
  nextJ++;
} else {
  nextI++;
}
for (int i = nextI; i < 5; i++){
  for (int j = nextJ; j < 5; j++) {
    if (arr[i][j] != 0 && arr[i][j] < min) min = arr[i][j];
  }
}

You can encapsulate everything in two methods

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question