代码之家  ›  专栏  ›  技术社区  ›  Ian Campbell

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

  •  5
  • Ian Campbell  · 技术社区  · 14 年前


    测试时(使用以下代码) char 'a' 是 10 ,以及的ASCII值 char 'b' 是 11 。 然而 ,连接时 字符“a” 和 字符'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
    

    为了子孙后代,我没有改变上面的代码来反映这一点。

    2 回复  |  直到 14 年前
        1
  •  5
  •   Marko Topolnik    14 年前

    您调用的方法错误: getNumericValue 将字符解释为数字。例如,一个十六进制数字 A 值为10。

    您应该做的只是直接使用您的char的值。将其投射到 int 例如。

        2
  •  3
  •   Dan D.    14 年前

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

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