简体   繁体   English

Java将int转换为char不起作用

[英]Java cast int to char doesn't work

I use Java 7 SE on Win7 Pro and have this problem: Converting int to char doesn't work properly. 我在Win7 Pro上使用Java 7 SE并遇到此问题:将int转换为char无法正常工作。

What is wrong? 怎么了?

Thanks. 谢谢。

int oneInt = 1;
char oneChar = '1';

// prints false
System.out.println((char) oneInt == oneChar);

// prints this symbol 
oneChar = (char) 1;
System.out.println(oneChar);

// Works - it prints 1 
oneChar = (1 + "").charAt(0);
System.out.println(oneChar);

The char '1' is not the same as the integer value 1 . char'1 '1'与整数值1 It's equals to the value of the ASCII code which represents '1' . 它等于表示'1'的ASCII码的值。 You can find all the ASCII values' encodings here 您可以在此处找到所有ASCII值的编码

If you want to convert a char into an integer like that, you need to subtract '0' (the character 0, not the integer) from it first. 如果要将char转换为类似的整数,则需要先从中减去'0' (字符0,而不是整数)。 Since all the integers are contiguous in ASCII, this will shift everything down so that '0' becomes 0 , '1' becomes 1 , etc. 由于所有整数在ASCII中是连续的,这将使所有内容都向下移动,以便'0'变为0'1'变为1 ,等等。

You might consider using some static method built into the standard Java libraries. 您可以考虑使用标准Java库中内置的一些静态方法。

For example, Integer.parseInt(String s) would take the string s and attempt to translate it to an integer. 例如,Integer.parseInt(String s)将获取字符串s并尝试将其转换为整数。 So Integer.parseInt("5") would return 5 as an integer. 所以Integer.parseInt(“5”)将返回5作为整数。

String.valueOf(int i) would turn the integer into its String equivalent. String.valueOf(int i)将整数转换为其String等价物。 So String.valueOf(10) would return "10" as a string. 所以String.valueOf(10)将返回“10”作为字符串。

If you're actually using chars and not just strings, this might help out: https://docs.oracle.com/javase/7/docs/api/java/lang/Character.html 如果您实际上使用的是chars而不仅仅是字符串,这可能会有所帮助: https//docs.oracle.com/javase/7/docs/api/java/lang/Character.html

There's methods like getNumericValue and isDigit. 有像getNumericValue和isDigit这样的方法。 Not sure if that's exactly what you're looking for, but it might be cleaner than using magic numbers like adding 48 to get the char you're looking for. 不确定这是否正是您正在寻找的,但它可能比使用魔术数字更清洁,例如添加48来获取您正在寻找的字符。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM