添加字符以获取ASCII值的目的是什么?

Ian*_*ell 5 java ascii char


当测试此(与下面的代码),对于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)



- 编辑: -

正如@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
Run Code Online (Sandbox Code Playgroud)

为了后人的缘故,我没有改变上面的代码来反映这一点.

Mar*_*nik 5

您正在调用错误的方法:getNumericValue将char解释为数字.例如,十六进制数字A的值为10.

你应该做的只是直接使用你的char的值.int例如,将它投射到一个.


Dan*_* D. 3

Character.getNumericValue()返回指定 Unicode 字符表示的 int 值。根据getNumericValue()Javadocs:“大写和小写的 A tp Z 字母都有从 10 到 35 的数值。这与 Unicode 规范无关,该规范不会为这些 char 值分配数值。”

但是,当您在concatChars()方法中添加它们时,添加的 2 个值是 ASCII 值 (97 + 98)。

  • 这是一个错误的解释。所有 ASCII 字符在 Unicode 中都具有完全相同的值。具体来说,Unicode 代码点 10 绝对不是 char *a*。 (3认同)
  • 是的,现在可以删除反对票。然而,当答案仍然不正确时,它确实得到了 5 个不应得的赞成票。 (2认同)