测试时(使用以下代码), ASCII 值为char 'a'
10 , ASCIIchar 'b'
值为11。但是,当连接char 'a'
and时char 'b'
,结果是195。
我的逻辑和/或理解中一定有错误......我确实知道字符不能连接为字符串,但是195的 ASCII int 值将代表什么?
这样的结果有什么用?
这是我的代码:
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
为了后代,我没有更改上面的代码来反映这一点。