How to place an increment inside a FOR loop?

Asked

Viewed 41 times

0

Please observe the code;

BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(getArquivo())));
        File arquivoLeitura = new File(getArquivo());
        LineNumberReader linhaLeitura = new LineNumberReader(new FileReader(arquivoLeitura));
        linhaLeitura.skip(arquivoLeitura.length());
        int qtdLinha  = linhaLeitura.getLineNumber() + 1;

        String linha = null;

        for (int i = 1; i  <= qtdLinha;  i++) {

                linha = reader.readLine();
                String[] dadosUsuario = linha.split(VIRGULA);
                System.out.println(Arrays.toString(dadosUsuario));
                System.out.println( dadosUsuario[0]);
                System.out.println( dadosUsuario[1]);

                System.out.println( dadosUsuario[2]);
                System.out.println( dadosUsuario[3]);
                System.out.println( dadosUsuario[4]);
                System.out.println(dadosUsuario[5]);
                System.out.println("--------------------------");

                if (pessoaJuridicaPublicaService.getPorId(Long.parseLong(dadosUsuario[1])) == null) {
                int j = j + 1;
                }



        }
            reader.close();

He’s making that mistake;

inserir a descrição da imagem aqui

If it’s a csv file upload, when I upload files, it goes through all the lines in the csv file;

inserir a descrição da imagem aqui

This line of code will check if one of the fields is empty, so I would like to count how many empty fields I can find in the data variable1.

The problem is that the FOR loop is not allowing me to place a counter within the IF condition. How do I fix this problem?

1 answer

1


The problem in your solution is that the variable j was created within the if which only exists in the if and cannot be used elsewhere. In addition to doing int j = j + 1; causes the variable to receive the value based on j that does not yet exist.

If you think about the instruction in Portuguese you understand the problem better: "Create a variable j and put the variable value on it j + 1." But if you have just created, then you cannot put the value based on a variable that does not exist.

Do it like this:

int j = 0; //declara fora do for

for (int i = 1; i  <= qtdLinha;  i++) {
    if (pessoaJuridicaPublicaService.getPorId(Long.parseLong(dadosUsuario[1])) == null) {
        j = j + 1; //apenas incrementa aqui
    }
}

It may not only make use of the ++ to simplify, as well as to give a better name to the variable:

int camposVazios = 0;

for (int i = 1; i  <= qtdLinha;  i++) {
    if (pessoaJuridicaPublicaService.getPorId(Long.parseLong(dadosUsuario[1])) == null) {
        camposVazios++;
    }
}

Browser other questions tagged

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