The task:

Create a program that introduces a square two-dimensional array of integers from the keyboard and replaces all elements lying on the main diagonal with the number of positive elements of the corresponding string, if there are any, or the maximum element if they are not. Print the resulting array to the screen.

Implementation:

package com.example.mas; public class arr6 { public static void main(String[] args) { int[][] a = {{4, 3, -1, -1}, {5, -2, 3, 1}, {0, 8, -9, 0}, {9, 5, 2, 0}}; int i, j, max, c; for (i = 0; i < 4; i++) { c = 0; max = a[i][0]; for (j = 0; j < 4; j++) { if (a[i][j] > 0) { c++; } if (a[i][j] > max) { max = a[i][j]; } if (a[i][j] < 0) { a[i][i] = c; } else { a[i][i] = max; } } } for (i = 0; i < a.length; i++) { for (j = 0; j < a.length; j++) { System.out.println(a[i][j]); } } } } 

    1 answer 1

    The assignment of a diagonal element must be outside the inner loop, and the number of positive elements must be involved in checking what to output (the number of positive elements or the maximum element):

     int[][] array = {{ 4, 3, -1, -1 }, { 5, -2, 3, 1 }, { -2, -8, -9, -5 }, { 9, 5, 2, 0 }}; for (int i = 0; i < array.length; i++) { int positiveNumbersCount = 0; int max = Integer.MIN_VALUE; for (int element : array[i]) { if (element > 0) { positiveNumbersCount++; } else if (element > max) { max = element; } } if (positiveNumbersCount > 0) { array[i][i] = positiveNumbersCount; } else { array[i][i] = max; } } for (int[] subArray : array) System.out.println(Arrays.toString(subArray));