Popular uma matriz com um arquivo

11 respostas
java
Thiago_Cavassini

Sou iniciante em prograação e não consigo popular uma matriz 58x58 usando um arquivo. Alguém poderia me ajudar ?

import java.io.BufferedReader;

import java.io.FileReader;

import java.io.IOException;

public class PCV {

public static void main(String[] args) throws IOException {
    
    int m[][]= new int [58][58];
    
    BufferedReader br;
    br = new BufferedReader(new FileReader("C:\\Users\\Thiago\\Desktop\\brazil58.tsp"));
    while(br.ready()){
    String linha = br.readLine();
    System.out.println(linha);
    
    }   
}

}

11 Respostas

confuso

Qual o erro que ocorre?

O que tem nesse arquivo brazil58.tsp? Pode mostrar exemplos de algumas linhas desse arquivo?

Que tipo de dado que é e como você quer que seja populado na matriz?

Thiago_Cavassini

Eu quero preencher minha matriz com inteiros, onde cada numero do arquivo seja colocado em uma posição da matriz. Aqui estão algumas linhas do arquivo para exemplo
520 86 3299 72 170 2864 558 662 1489 856 1434
543 2931 448 342 2495 239 288 1797 1266 1878
3295 97 199 2859 588 692 1637 858 1339
3227 3206 446 2750 2649 4617 2417 1882
102 2791 486 590 1535 8700 1441
2770 389 497 1514 888 1543
2314 2213 4181 2105 1446
112 1972 994 1345
2076 1057 1408
2328 2986
962

confuso

Okay, entendi. Mas percebi que cada linha tem números diferentes de números. Então, o arquivo em si não é uma representação exata de uma matriz, certo? Como você quer que seja decidido qual número vai em qual posição da matriz?

Thiago_Cavassini

Sim , ela não é uma matriz exata, porém queria colocar esses dados conforme cada espaço em branco mudasse a posição da matriz e cada vez que pular a linha mudar a linha da matriz também.

confuso

Entendi, então a matriz do Java teria muitas posições vazias.

A matriz poderia ser uma matriz de Integer[][] (em vez de int[][]) e os espaços vazios serem representados como null, não teria problema, né?

E você tem como saber a largura máxima da matriz (quantidade máxima de números que terá uma linha nesse arquivo)?

Thiago_Cavassini

A largura máxima é 58 e o numero de linhas são 58 , por isso criei a matriz 58x58, mas uma matriz dinamica seria ótimo também.

Thiago_Cavassini

Adicionei mais algumas linhas no meu código, acho que a lógica está correta, porém dá um erro
Exception in thread “main” java.lang.NumberFormatException: For input string: “NAME: brazil58”

public static void main(String[] args) throws IOException {

Integer m[][] = new Integer[58][58];

    BufferedReader br = new BufferedReader(new FileReader("C:\\Users\\Thiago\\Desktop\\brazil58.tsp"));
    String texto = br.readLine();
    
    while ((texto ) != null) {
        for (int i = 0; i < m.length; i++) {
            for (int j = 0; j < m.length; j++) {
                m[i][j] = Integer.parseInt(texto);
            }
        }
    }
    for (int i = 0; i < m.length; i++, System.out.println("\n")) {
        for (int j = 0; j < m.length; j++) {
            System.out.print(m[i][j] + " ");
        }
    }
}
confuso

Terminei. Isso funciona, mas o problema é que a matriz fica muitas linhas desnecessárias. Pode testar se funciona com o seu arquivo?

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.security.InvalidParameterException;

public class Programa {

public static void main(String[] args) throws IOException {
    Programa programa = new Programa();

    String nomeDoArquivo = "C:\\Users\\Thiago\\Desktop\\brazil58.tsp";
    final int larguraMaxima = 58;
    final int alturaMaxima = 58;

    Integer[][] transformadaEmMatriz = programa.lerArquivoEmMatriz(nomeDoArquivo, larguraMaxima, alturaMaxima);

    programa.exibirMatriz(transformadaEmMatriz);
}

public Integer[][] lerArquivoEmMatriz(String nomeDoArquivo, int larguraMaxima, int alturaMaxima) throws IOException {
    Integer matriz[][] = new Integer[alturaMaxima][larguraMaxima];

    BufferedReader leitorDeLinhas = new BufferedReader(new FileReader(nomeDoArquivo));

    int linhaAtual = -1;

    String linha;
    while ((linha = leitorDeLinhas.readLine()) != null) {
        String[] numerosString = linha.split(" ");

        if (numerosString.length > larguraMaxima) {
            throw new InvalidParameterException("Erro! Esta linha contém mais números do que o suportado para quantidade de colunas da matriz.");
        }

        linhaAtual++;

        Integer[] linhaDeIntegers = transformarEmLinhaDeIntegers(numerosString);
        matriz[linhaAtual] = linhaDeIntegers;
    }

    return matriz;
}

private Integer[] transformarEmLinhaDeIntegers(String[] numerosEmString) {
    Integer[] numeros = new Integer[numerosEmString.length];

    for (int i = 0; i < numeros.length; i++) {
        numeros[i] = transformarEmNumero(numerosEmString[i]);
    }

    return numeros;
}

private Integer transformarEmNumero(String numeroEmString) {
    try {
        return Integer.valueOf(numeroEmString.trim());
    } catch (NumberFormatException e) {
        System.out.println("Não foi possível converter a String '" + numeroEmString + "' para Integer. Será retornado 'null'. Mensagem de erro: " + e.getMessage());
        return null;
    }
}

private void exibirMatriz(Integer[][] matriz) {
    for (Integer[] linha : matriz) {
        for (Integer valor : linha) {
            System.out.print(valor + " ");
        }
        System.out.println();
    }
}
}

Qualquer linha que você não entendeu pode me perguntar.

Resultado:

Screenshot%20from%202019-05-02%2014-28-46

Thiago_Cavassini

Muito obrigado mesmoo !! Preciso ir pra aula agora , se eu tiver alguma duvida pergunto aqui depois. Muito obrigado mesmo !!

staroski

Realmente, não dá pra converter "NAME: brazil58" em um número.

staroski

Não precisa nesessariamente criar um new int[58][58] já que o número de elementos da linhas vai variar, cria simplesmente um new int[58][].

Veja:

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class Exemplo {

    public static void main(String[] args) {
        try {
            Exemplo programa = new Exemplo();
            programa.executar();
        } catch (Throwable t) {
            t.printStackTrace();
        }
    }

    public void executar() throws Exception {
        int[][] matriz = lerArquivoEmMatriz("C:\\Users\\Thiago\\Desktop\\brazil58.tsp");
        exibir(matriz);
    }

    public int[][] lerArquivoEmMatriz(String caminho) throws IOException {
        int[][] matriz = new int[58][]; // a segunda dimensão vai variar de acordo com a quantidade de numeros em cada linha
        BufferedReader reader = new BufferedReader(new FileReader(caminho));
        int posicao = 0;
        String linha;
        while ((linha = reader.readLine()) != null) {
            String[] strings = linha.split(" ");
            int tamanho = strings.length;
            int[] numeros = new int[tamanho];
            for (int i = 0; i < tamanho; i++) {
                numeros[i] = Integer.parseInt(strings[i]);
            }
            matriz[posicao] = numeros;
        }
        reader.close();
        return matriz;
    }

    private void exibir(int[][] matriz) {
        for (int[] linha : matriz) {
            for (int numero : linha) {
                System.out.print(" " + numero);
            }
            System.out.println();
        }
    }
}
Criado 2 de maio de 2019
Ultima resposta 2 de mai. de 2019
Respostas 11
Participantes 3