Dylan Dylan - 3 years ago 147
Java Question

char digit to integer conversion

I'm getting the user to enter a string of numbers, then a for loop should pick out each number from the string and add it to an

. I'm sure someone can help me out fairly quickly

My problem is as follows. When I print out all the values in the
, It is printing out much higher numbers e.g.
1234 = 49 50 51 52

I think what is happening is that it is printing out the
values rather than the numbers themselves. Can anyone spot where and why this is happening?

I have tried changing the
variable barcodeNumberAtI to a
, which yields the same result.

Apologies for lack of comments but this was only supposed to be a quick program

int tempNewDigit;
String barCode, ans;
int barcodeNumberAtI;
ArrayList <Integer> numbers = new ArrayList <Integer>();

public void addNumbers(){

Scanner s = new Scanner(System.in);

System.out.println("Please enter a 12 digit barcode\n");
barCode = s.nextLine();

for(int i = 0; i < barCode.length(); i++){

barcodeNumberAtI = barCode.charAt(i);


System.out.print("Would you like to add another? y/n\n");
ans = s.nextLine();
} while (!ans.equals("n"));

public void displayNumbers(){

for(int i = 0; i < numbers.size(); i++){


Answer Source

Happens at this line: barcodeNumberAtI = barCode.charAt(i);

barCode.charAt(i) returns a char which is converted to a int by using its ASCII value.

Use this instead:

barcodeNumberAtI = Character.digit(barCode.charAt(i), 10);

What Character.digit does is converting its first argument from the type char to the corresponding int in the radix specified by the second argument. Here's a link to the documentation

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download