Array returns wrong value in java

Asked

Viewed 99 times

0

I have a question about a college job. I can read with numbers, remove ";" and pass the values to the array while reading the file. However, when I try to access a position of the array outside of reading the file, it does not return the value I have in the file but another value. If anyone can help, thank you.

ARCHIVE I READ

10
1;1;1
2;2;3;2;150;20
3;3;3;1;100;10
4;4;3;4;350;30
5;5;3;1;100;10
6;6;3;2;150;20
7;7;3;3;100;10
8;8;3;5;500;10
9;9;2
10;10;3;1;100;10

EXIT FROM THE PROGRAMME

10
1
1
1
2
2
3
2
150
20

and so on ...

If I want to read the number 2 that is in the 5th position of the output, I do:

 System.out.println(array[4]);

and instead of returning the number 2 it returns the 100.

MY CODE

package jogo;

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


public class Tabuleiro {

private static BufferedReader br;

public static void main(String[] args) {

        String[] array = null;

        try {
            br = new BufferedReader(new FileReader("/home/overwatch/tabuleiro1.txt"));
            String linha = br.readLine();

            while(linha!=null){
                array = linha.split(";");
                linha = br.readLine();

                for(int i=0; i < array.length;i++){
                    System.out.println(array[i]);
                }
            }   
            br.close();

            //imprimindo o 3 valor que está no array
            System.out.println(array[4]);

        } catch (IOException ioe) {
            ioe.printStackTrace();
        }
    }
}

2 answers

1


In this code here:

while(linha!=null){
    array = linha.split(";");

 ...
}

You are overwriting the array at each iteration in while. At the end your array will only be with the values of the last line of the file ("10;10;3;1;100;10") where position 4 really is value 100. Your code is displaying on the screen all values of each line of the file, but storing in the array only the last line read. You could use an Arraylist to store the values like this:

    public class Tabuleiro {

    private static BufferedReader br;

    public static void main(String[] args) {

        ArrayList<String> array = new ArrayList<>();

        try {
            br = new BufferedReader(new FileReader("/home/overwatch/tabuleiro1.txt"));
            String linha = br.readLine();

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

                for (int i = 0; i < lineValues.length; i++) {
                    array.add(lineValues[i]);
                    System.out.println(lineValues[i]);
                }
            }
            br.close();

            // imprimindo o 3 valor que está no array
            System.out.println(array.get(4));

        } catch (IOException ioe) {
            ioe.printStackTrace();
        }
    }
}
  • I’m glad you had to change so little in my code... thanks for the explanation and solution :)

0

You are not storing in the array every line you read. A proposal is to do so:

 public static List<String> leExibeArquivo(String arquivo) {
        String s, temp;            
        //   HashSet<String> valores = new HashSet<>();//ArrayList antes
        List<String> valores = new ArrayList();
        int i = 0;
        System.out.println("O arquivo aberto é: " + arquivo);
        System.out.println("Exibindo arquivo:");
        try (BufferedReader br = new BufferedReader(new FileReader(arquivo))) {
            while ((s = br.readLine()) != null) {
                System.out.println(s);
                valores.add(s);
            }
        } catch (IOException exc) {
            System.out.println("Erro de E/S " + exc);
        }

        return valores;
    }

You would call the method so:

 List<String> linhas = new ArrayList<String>();
            String arquivo = "/home/overwatch/tabuleiro1.txt";
            linhas = leExibeArquivo(arquivo);//recebe o arquivo em um ArrayList, cada posição uma linha
            //o retorno do método leExibeArquivo(String) é um ArrayList

And then it could convert to a normal array as follows:

Object vetorLinhas[] = linhas.toArray();    //converte o ArrayList com as linhas para um array.

        System.out.println("Exibe o vetor com as linhas:"); //cada linha em um aposição do vetor - vai ser usado para comparar
        for (int i = 0; i < vetorLinhas.length; i++) {
            System.out.printf("linhas[%d]= %s\n", i+1, vetorLinhas[i]);   //exibe-o na tela
        }

After that you could call any position directly as the example itself already demonstrates (using vetorLinhas[i])

Got it?

Anything is just go in the comments!

  • Of course, in the leExibeArchive method you would use the normal split as you are doing to ignore the ;

  • Thank you for the solution :)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.