开发者

(To me) unexplainable value in character array

I'm stuck with something I really don't understand and I hope someone over here does.

Can anybody explain me why 'nextOne' holds the value 51? It's clear that at index 2 in the expression array is the number 3 so why does it store 51 in s开发者_StackOverflowtead of 3 in nextOne?

Here it is:

(To me) unexplainable value in character array


The character in the array is '3'. That has a Unicode value of 51 - it's character U+0033.

If you change the type of nextOne to char instead of int, you'll see '3' instead.

It's important to understand the difference between digits as characters, and integer values - and also to understand the numbers which lurk behind characters; in Java they're UTF-16 code units, basically.


Because 51 is the ASCII value for the numeral 3.


The character '3' corresponds to an integer value of 51 (it's ascii/unicode value).


The first digit is 3 and its ASCII code is 51.


nextOne contains the value of the character, which, in the case of the character '3' is 51.

If you want the digit represented by the character, you need to convert it. With ASCII, that can be done by subtracting the value of the character '0'.


51 is the ASCII code for three, since expression is an array of chars, and nextOne is an int, you have to convert the char to an int


The ASCII code of the number 3 is 51. The following expression will print "true" in the console.

System.out.println('3' == (char) 51);

Have a look at an ASCII table for more information.


you see the ascii code of the character '3' if you want the digit you need to subtract '0' to get the integer value


I did it! It works now and I couldn't have done it without you guys. However! Funny how all of you suggested options for me but not the (in my opinion) ultimate one. You guys told me the integer that was being stored is the ASCII code for 3, not the actual integer 3. That reminded me of a method in the Character class, getNumericValue(char). With this method I simply retrieved the integer 3 from the char array without converting myself.

nextNumber = nextNumber * 10 + Character.getNumericValue(expression[k]);

Thanks @howard for editing the link into the uploaded image

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜