-2
There is an error mentioned in the question in my java program.
The program is a barcode reader. The user informs the digits of the code (except the last one). The sum of the numbers q are in odd position, and those in odd position. Then there are other calculations (which I will do later) that result in the last digit (the one that was not informed by the user).
I reduced it to 12 to 4 digits informed by the user, to make it easier to follow the code. It is running, but when arriving on line 26 gives error (first is, but I believe in the second too):
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’ve tried to change the condition of the i < 5
for i == 4
, put other values, but still giving error.
got it... but wouldn’t it be better to use i <= code.length ? and if I put the i++, then I should put a condition that only execute if the number is odd, right? pq otherwise it will add even with odd...
– Jow
i <= codigo.length
does not meet because the initial character of the string is position 0, so going from 0 to the maximum size, you would have an extra position (generating the current error)– rLinhares
as regards the
i++
, I think you can improve your method a little, since it always uses a single character.int numConvertido = Integer.parseInt(codigo[i]);
. Thus it will convert only the correct digit. With this you can even keep the condition ofi = i + 2
because the error displayed does not occur– rLinhares
was wrong. Fixing java conversion:
int numConvertido = Character.getNumericValue(codigo.charAt(i));
– rLinhares
gave right! thanks, pal. dps I’ll give a survey to better understand this
Character.getNumericValue
.– Jow