# java – Count rows in matrix that have repeated numbers

## Question:

I would like to add the `linhaPreta` to the number of lines only with 0, and the `linhaBranca` only with 1.

``````public class Pixel {
public static void main(String[] args) {

int[][] img = {
{ 1, 1, 1, 1, 1, 1, 1, 1 },
{ 0, 1, 0, 1, 1, 1, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0 },
{ 1, 1, 1, 1, 1, 1, 1, 1 },
{ 1, 1, 1, 1, 1, 1, 1, 1 },
{ 1, 1, 1, 1, 1, 1, 1, 1 },
{ 1, 1, 0, 0, 1, 1, 1, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0 },};

int ppreto = 0;
int pbranco = 0;
int linhaPreta = 0;
int linhaBranca = 0;

int i;
int j = 0;

for (i = 0; i < img.length; i++) {
for (j = 0; j < img[i].length; j++) {

if (img[i][j] == 0) {
ppreto++;
}

if (img[i][j] == 1) {
pbranco++;
}

if (img[i].length == 0) {
linhaPreta++;
}
if (img[i].length == 0) {
linhaBranca++;
}
}
}

System.out.print("qtde ponto preto = " + ppreto + "\n");
System.out.print("qtde ponto branco = " + pbranco + "\n");
System.out.print("Qtd linha preta = " + linhaPreta + "\n");
System.out.print("Qtd linha branca= " + linhaBranca + "\n");
}
}
``````

Simple solution suggestion:

For each "line" in your image, add the pixels together. If the sum is zero (0) the line is "all black". If the sum equals the number of pixels in the line, the line is "all white".

``````int[][] img = {
{ 1, 1, 1, 1, 1, 1, 1, 1 },
{ 0, 1, 0, 1, 1, 1, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0 },
{ 1, 1, 1, 1, 1, 1, 1, 1 },
{ 1, 1, 1, 1, 1, 1, 1, 1 },
{ 1, 1, 1, 1, 1, 1, 1, 1 },
{ 1, 1, 0, 0, 1, 1, 1, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0 },};

int linhaPreta = 0;
int linhaBranca = 0;

for (int i = 0; i < img.length; i++) {

int soma = 0;
for (int j = 0; j < img[i].length; j++)
soma += img[i][j];

if(soma == 0)
linhaPreta++;
else if(soma == img[i].length)
linhaBranca++;
}
``````
Scroll to Top