在Java中将字符转换为整数

编程入门 行业动态 更新时间:2024-10-24 14:26:22
本文介绍了在Java中将字符转换为整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

谁能给我解释一下这里发生了什么:

Can someone please explain to me what is going on here:

char c = '+'; int i = (int)c; System.out.println("i: " + i + " ch: " + Character.getNumericValue(c));

这将打印 i: 43 ch:-1.这是否意味着我必须依靠原始转换将 char 转换为 int?那么如何将 Character 转换为 Integer?

This prints i: 43 ch:-1. Does that mean I have to rely on primitive conversions to convert char to int? So how can I convert a Character to Integer?

是的,我知道如果 Character.getNumericValue 不是数值,那么它会返回 -1,这对我来说很有意义.问题是:为什么进行原始转换会返回 43?

Yes I know Character.getNumericValue returns -1 if it is not a numeric value and that makes sense to me. The question is: why does doing primitive conversions return 43?

Edit2: 43 是 + 的 ASCII,但我希望转换不会像 getNumericValue 没有成功.否则这意味着有两种语义等效的方式来执行相同的操作但结果不同?

43 is the ASCII for +, but I would expect the cast to not succeed just like getNumericValue did not succeed. Otherwise that means there are two semantic equivalent ways to perform the same operation but with different results?

推荐答案

Character.getNumericValue(c)

java.lang.Character.getNumericValue(char ch) 返回指定 Unicode 字符所代表的 int 值.例如,字符 'u216C'(罗马数字 50)将返回一个值为 50 的 int.

The java.lang.Character.getNumericValue(char ch) returns the int value that the specified Unicode character represents. For example, the character 'u216C' (the roman numeral fifty) will return an int with a value of 50.

字母 AZ 大写 ('u0041' 到 'u005A')、小写 ('u0061' 到 'u007A') 和完整宽度变体 ('uFF21' 到 'uFF3A' 和 'uFF41' 到 'uFF5A') 形式的数值从 10 到 35.这与 Unicode 规范无关,它不为这些 char 值分配数值.

The letters A-Z in their uppercase ('u0041' through 'u005A'), lowercase ('u0061' through 'u007A'), and full width variant ('uFF21' through 'uFF3A' and 'uFF41' through 'uFF5A') forms have numeric values from 10 through 35. This is independent of the Unicode specification, which does not assign numeric values to these char values.

此方法返回字符的数值,作为非负整数值;

This method returns the numeric value of the character, as a nonnegative int value;

-2 如果字符的数值不是非负整数;

-2 if the character has a numeric value that is not a nonnegative integer;

-1 如果字符没有数值.

-1 if the character has no numeric value.

这里是链接.

更多推荐

在Java中将字符转换为整数

本文发布于:2023-10-24 16:54:10,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1524492.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:整数   转换为   中将   字符   Java

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!