在一个整数中返回多个数字

时间:2015-01-19 22:44:57

标签: java string char

这是我将字符转换为数字的简单代码(因为那时我将不得不进行冒泡排序。)我想返回一个整数,它是我字符的Ascii的组合。 例如,如果我有一个类似" b78"的字符串。我的方法" ascii"应该做这样的事情:

'b' = 98, '7' = 55, '8'= 56

但我希望将其作为一个整数返回:985556。我想只返回一个整数,不是数组,int []。我该怎么做才能做到这一点?

public class Example{
    public static int ascii(String s){ 
        for(int i=0 ; i < s.length() ; i++){
            char c = s.charAt(i);
            int j= (int)c;
        }
        // I don,t know what I have to return
    }
    public static void main(String[] args){
        String[] str = {"b78","c&3","a00","a01","zz9"};
        String q = str[0];

        int c = ascii(q);
        System.out.print(c);
    }
}

2 个答案:

答案 0 :(得分:0)

根据您提供的示例,我认为您需要类似

的内容
public static int ascii(String s) {
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < s.length(); i++) {
        char c = s.charAt(i);
        sb.append(Integer.toString(c));
    }
    return Integer.parseInt(sb.toString());
}

public static void main(String[] args) {
    String[] str = { "b78", "c&3", "a00", "a01", "zz9" };
    for (String q : str) {
        int c = ascii(q);
        System.out.printf("%s %d%n", q, c);
    }
}

输出

b78 985556
c&3 993851
a00 974848
a01 974849
zz9 12212257

答案 1 :(得分:0)

我不明白你为什么尝试这个,但我认为你可以使用字符串连接的+运算符。将每个字符转换为ASCII并使用Integer.toString()将此整数转换为字符串。然后用+运算符连接它们,并再次使用Integer.parseInt(String str)方法再次转换结果。我想你可以得到你想要的结果。

相关问题