An alternative to summing the values of the matrix is to use the Enhanced for (which some call "foreach"):
int matriz[][] = new int[10][10];
...
// assumindo que a matriz já está com os valores preenchidos
int soma = 0;
for (int[] linha : matriz) {
for (int valor : linha) {
soma += valor;
}
}
There are no actual matrices in Java, and to simulate them we can use arrays of arrays. So matriz
is actually an array, and every element of it is another array (and nothing prevents the "lines" of the "matrix" from being of different sizes).
So in the first for
I declare int[] linha
, because each element of the matrix is an array of int
(one int[]
). Then just go through this array with another for
, where each element is one int
.
This syntax has a limitation, which is not having access to the indexes. So you couldn’t use it to fill the values of the matrix. That is, the code below does not work:
for (int[] linha : matriz) {
for (int valor : linha) {
valor = 1; // NÃO FUNCIONA, o valor da matriz não é alterado
}
}
In this case, the only way is to make one for
traditional, as per the answer from Daniel. But if you just want to access the values, without needing the index, the Enhanced for is an alternative.
Another alternative to summing the values, if using Java >= 8, is to use streams:
int soma = Arrays.stream(matriz).flatMapToInt(linha -> Arrays.stream(linha)).sum();
Arrays.stream
converts the matriz
for a stream of int[]
, and flatMapToInt
converts each row of the matrix (i.e., each int[]
) for a IntStream
. The result is a IntStream
containing all matrix numbers.
Finally, the method sum()
returns the sum of all numbers.
It is worth remembering that in this case, maybe it is exaggerated to use streams, for they have their cost and are slower than a loop traditional.
You don’t need to put "solved" in the title. I know that in many forums it is common to do this, but you don’t need it here. You have already accepted the answer below and that is enough for others to know that the problem has been solved.
– hkotsubo