如何计算ASCII的总和?

时间:2015-11-09 14:19:22

标签: java

我想计算从“E”到最后一个“破折号”变量的每个变量和字符串的总和,目前它只计算“消息”变量:

physicalLayer.sendFrame(open + "E" + dash + length + dash + message + dash + total + close);

这是我的完整代码:

String open = "<";
String close = ">";
String dash = "-";
int length = message.length();
int total = 0;

    for(int i=0; i < message.length(); i++)
    {
        int mod = message.charAt(i);
        total += mod;
    }

physicalLayer.sendFrame(open + "E" + dash + length + dash + message + dash + total + close);

例如

输入消息是:

hello

输出消息:

<E-05-hello-532>

1 个答案:

答案 0 :(得分:1)

String message = "hello java";
String open = "<";
String close = ">";
String dash = "-";
int length = message.length();
int total = 0;

String str = "E-" + (length < 10 ? "0" : "") + length + "-" + message + "-";
for (int i = 0; i < str.length(); i++) {
    int mod = str.charAt(i);
    total += mod;
}
String output = open + str + total + close;
System.out.println(output);