当测试以下代码时,char'a'
的ASCII值为10,char 'b'
的ASCII值为11。然而,在连接char 'a'
和char 'b'
时,结果是195。
我的逻辑和/或理解中一定有错误...我确实知道char不能作为字符串连接,但是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.
-- EDIT : --
正如@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
我为了记录的缘故,没有修改上述代码。
concatChars
,它应该被命名为类似于addChars
的东西。 - Ian Campbell