"String index out of range: 5"

-2

The error mentioned in the question in my program in java is occurring.

The program is a bar code reader. The user informs the code digits (with the exception of the last one). The sum of the numbers q is in the odd position, and the odd numbers. Then there are other calculations (which I will make further) that result in the last digit (the one that was not entered by the user).

I reduced to 12 to 4 digits entered by the user, to make it simpler to follow the code. It is running, but on arriving at line 26 it gives error (first is, but I believe in the second as well):

import java.util.Scanner;

public class Main {
    public static void main (String[] args) {

        Scanner sc = new Scanner(System.in);
        String codigo;

        do {
            System.out.println("\n\nInforme os primeiros 4 caracteres do codigo de barras: \n");
            codigo = sc.nextLine();

            if (codigo.length() != 4) {
                System.out.println("\n\nO numero informado nao corresponde a 4 caracteres.");
            }

        } while (codigo.length() != 4); 

        int somaImpar = 0;

        for (int i = 0; i <= codigo.length(); i = i + 2) {
            int numConvertido = Integer.parseInt(codigo.substring(i, (i + 1)));
            System.out.println("i: " + i);
            somaImpar = somaImpar + numConvertido;

            if (i == 2) {
                System.out.println("Soma dos impares: " + somaImpar);
            }
        }

        int somaPar = 0;

        for (int i = 1; i <= codigo.length(); i = i + 2) {
            int numConvertido2 = Integer.parseInt(codigo.substring(i, (i + 1)));
            System.out.println("i: " + i);
            somaPar = somaPar + numConvertido2;

            if (i == 3) {
                System.out.println("Soma dos pares: " + somaPar);
            }
        }
    } 
}

I have tried to change the condition of the from i < 5 to i == 4 , put other values, but still giving error.

    
asked by anonymous 31.08.2017 / 19:10

1 answer

1

The problem is yes in its for (and would happen in both).

for (int i = 0; i < 5; i = i + 2)

You say that it should iterate while the i is less than 5; commands the user to enter 4 numbers. It's already a problem, because if you go through the digits one by one you would have a total of 5 (positions 0, 1, 2, 3 and 4 of the codigo variable).

But your error bursts in this line:

int numConvertido = Integer.parseInt(codigo.substring(i, (i + 1)));

Your counter increments two by iterating for ( i = i + 2 ), so think of the third execution, when i = 4; the numConvertido will receive codigo.substring(4, 5) , when in fact the code only has 4 digits.

You need to review this for both points:

  • the stop condition should be i < codigo.length()
  • the iteration should be only one ( i++ )
31.08.2017 / 19:18