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.