对此进行测试时(使用以下代码),char 'a'
的 ASCII 值为 10,char 'b'
的 ASCII 值为> 是 11。 但是,当连接char 'a'
和char 'b'
时,结果是195。
我的逻辑和/或理解一定有错误...我确实明白字符不能作为字符串连接,但是 195 然后代表?
这样的结果有什么用?
这是我的代码:
public class Concatenated
{
public static void main(String[] args)
{
char char1 = 'a';
char char2 = 'b';
String str1 = "abc";
String result = "";
int intResult = 0;
Concatenated obj = new Concatenated();
// calling methods here
intResult = obj.getASCII(char1);
System.out.println("The ASCII value of char \"" + char1 + "\" is: " + intResult + ".");
intResult = obj.getASCII(char2);
System.out.println("The ASCII value of char \"" + char2 + "\" is: " + intResult + ".");
result = obj.concatChars(char1, char2);
System.out.println(char1 + " + " + char2 + " = " + result + ".");
result = obj.concatCharString(char1, str1);
System.out.println("The char \"" + char1 + "\" + the String \"" + str1 + "\" = " + result + ".");
} // end of main method
public int getASCII(char testChar)
{
int ans = Character.getNumericValue(testChar);
return ans;
} // end of method getASCII
public String concatChars(char firstChar, char secondChar)
{
String ans = "";
ans += firstChar + secondChar; // "+=" is executed last
return ans; // returns ASCII value
} // end of method concatChars
public String concatCharString(char firstChar, String str)
{
String ans = "";
ans += firstChar + str;
return ans;
} // end of method concatCharString
} // end of class Concatenated
...打印到屏幕的结果如下:
The ASCII value of char "a" is: 10.
The ASCII value of char "b" is: 11.
a + b = 195.
The char "a" + the String "abc" = aabc.
-- 编辑:--
正如@Marko Topolnik 在下面指出的那样,方法
getASCII
应该更改为此以返回正确的 ASCII 值(并且不是 UNICODE 值):
public int getASCII(char testChar)
{
// int ans = Character.getNumericValue(testChar); ...returns a UNICODE value!
int ans = testChar;
return ans;
} // end of method getASCII
为了后代,我没有更改上面的代码来反射(reflect)这一点。
最佳答案
您调用了错误的方法:getNumericValue
将 char 解释为数字。例如,十六进制数字 A
的值为 10。
您应该做的是直接使用 char 的值。例如,将其转换为 int
。
关于java - 添加字符以获得 ASCII 值的目的是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12133825/