当测试此(与下面的代码),对于ASCII值char 'a'是10,而对于ASCII值char 'b'是11.然而,当串联char 'a'和char 'b',结果是195.
必须有我的逻辑和/或理解这里的错误...我不明白,字符不能串联为一个字符串,但你会的ASCII int值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
Run Code Online (Sandbox Code Playgroud)
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.
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)
为了后人的缘故,我没有改变上面的代码来反映这一点.
您正在调用错误的方法:getNumericValue将char解释为数字.例如,十六进制数字A的值为10.
你应该做的只是直接使用你的char的值.int例如,将它投射到一个.
Character.getNumericValue()返回指定 Unicode 字符表示的 int 值。根据getNumericValue()Javadocs:“大写和小写的 A tp Z 字母都有从 10 到 35 的数值。这与 Unicode 规范无关,该规范不会为这些 char 值分配数值。”
但是,当您在concatChars()方法中添加它们时,添加的 2 个值是 ASCII 值 (97 + 98)。
| 归档时间: |
|
| 查看次数: |
1687 次 |
| 最近记录: |