JayCesar / java-springboot

[📚 Study ] This repository was created to add files and my notes from the course POO of Java ( + spring);
2 stars 0 forks source link

Dificuldade com Matrizes #15

Closed JayCesar closed 1 year ago

JayCesar commented 1 year ago

Eu encontrei dificuldade com matrizes na parte que envolve buscar itens nas posições dentro dela

Exercício: Fazer um programa para ler dois números inteiros M e N, e depois ler uma matriz de M linhas por N colunas contendo números inteiros, podendo haver repetições. Em seguida, ler um número inteiro X que pertence à matriz. Para cada ocorrência de X, mostrar os valores à esquerda, acima, à direita e abaixo de X, quando houver, conforme exemplo

Exemplo 2023-04-22_08h56_42

Código:

package classes;

import java.util.Locale;
import java.util.Scanner;

public class MatrizExercise {

    public static void main(String[] args) {
        Locale.setDefault(Locale.US);
        Scanner sc = new Scanner(System.in);

        int M = sc.nextInt();
        int N = sc.nextInt();

        int[][] mat = new int[M][N];

        for (int i = 0; i < mat.length; i++) {
            for (int j = 0; j < mat[i].length; j ++) {
                mat[i][j] = sc.nextInt();
            }
        }

        int X = sc.nextInt();

        for (int i = 0; i < mat.length; i++) {
            for (int j = 0; j < mat[i].length; j++) {
                if (mat[i][j] == X) {
                    System.out.print("Position: " + i + ", " + j + ": \n");
                    if (j > 0) {
                        System.out.println("Left: " + mat[i][j-1]);
                    }   
                    if (i > 0) {
                        System.out.println("Up: " + mat[i - 1][j]);
                    }
                    if (j < mat[i].length-1) {
                        System.out.println("Right: " + mat[i][j+1]);
                    }
                    if (i < mat.length-1) {
                        System.out.println("Down: " + mat[i+1][j]);
                    }

                }
            }
        }

        sc.close();

    }

}
JayCesar commented 1 year ago

PDF: 05-memoria-arrays-e-listas (1).pdf