Дана матрица 4x4. Нужно найти сумму наибольших элементов строк матрицы. Алгоритм создал, но, бывает, выдает отрицательные числа. Я думаю, проблема в том, что когда элементы строки матрицы, следующие за первым и больше первого, повторяются, алгоритм не срабатывает.
35 30 35 20
15 15 25 25
35 30 20 15
20 15 35 20
Помогите решить это. Алгоритм в коде помечен комментарием.
Код:
class Lab2
{
public static void main(String[] args)
{
byte a = 5;
byte sum = 0, max;
byte B[][] = new byte[4][4];
byte C[][] = new byte[4][4];
for(int i = 0; i < 4; i++)
{
for(int j = 0; j < 4; j++)
{
B[i][j] = (byte) (3 + (int) (Math.random() * 5));
}
}
System.out.println("Matrix B:");
for(int i = 0; i < 4; i++)
{
for(int j = 0; j < 4; j++)
{
System.out.print(B[i][j] + " ");
}
System.out.println();
}
for(int i = 0; i < 4; i++)
{
for(int j = 0; j < 4; j++)
{
C[i][j] = (byte) (B[i][j] * a);
}
}
System.out.println("Matrix C:");
for(int i = 0; i < 4; i++)
{
for(int j = 0; j < 4; j++)
{
System.out.print(C[i][j] + " ");
}
System.out.println();
}
//counting the sum of the greatest elements of each row
for(int i = 0; i < 4; i++) // ПРОБЛЕМА ЗДЕСЬ
{
max = C[i][0];
for(int j = 1; j < 4; j++)
{
if(C[i][j] > max)
{
max = C[i][j];
}
}
sum += max;
}
System.out.println("The sum of the greatest elements of each row is: " + sum);
}
}