Usar uma matriz criada dentro do if no resto do codigo

1 resposta Resolvido
K

boa noite galera, esse e meu primeiro post aqui no GUJ, estou com um problema que julgo ser simples.

private static double[][] soma(double[][] matriz1, double[][] matriz2) {

if(matriz1.length == matriz2.length && matriz1[0].length == matriz2[0].length) {

double[][] R = new double[matriz1.length][matriz2[0].length];

}else {

System.out.println(Soma nao e possivel pois as matrizes tem dimencoes diferentes!);

}

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

for(int j = 0; j < R[0].length; j++) {

R[i][j]= matriz1[i][j] + matriz2[i][j];

System.out.print(R[i][j] + " ");

}

System.out.println();

}

return R;			

}

O problema e que a matriz R so existe dentro do if. Como posso usar ela fora do if?
Estou tentando implementar isso como um método de uma classe matriz, com um construtor:

matriz A = new matriz(i, j);

matriz B = new matriz(i, j);

matriz C = new matriz(i, j);

identidade(A);                             \esse ja consegui, faz a matriz A ser uma matriz identidade

identidade(B);

alteraValor(A, 2 , 1 , 10.0);         \ nesse eu passo a matriz, a posicao (i,j) e o valor que quero

\  atribuir.

C.soma(A , B)                            \ nessa nao sei como fazer

1 Resposta

wldomiciano
Solucao aceita

Seja bem vindo. Ao postar seus códigos, use as tags apropriadas, escrevi sobre isso aqui:

Sobre sua dúvida… Declare a variável fora do if.

private static double[][] soma(double[][] matriz1, double[][] matriz2) {
    double[][] R = new double[0][0]; // se o length das matrizes forem diferentes, vc retornará um array de tamanho zero

    if(matriz1.length == matriz2.length && matriz1[0].length == matriz2[0].length) {
        R = new double[matriz1.length][matriz2[0].length];
    }else {
        System.out.println("Soma nao e possivel pois as matrizes tem dimencoes diferentes!");
    }

    for(int i = 0; i < R.length ; i++) {
        for(int j = 0; j < R[0].length; j++) {
            R[i][j]= matriz1[i][j] + matriz2[i][j];
            System.out.print(R[i][j] + " ");
        }
        System.out.println();
    }

    return R;
}
Criado 29 de abril de 2018
Ultima resposta 30 de abr. de 2018
Respostas 1
Participantes 2