Java,将字符串转换为整数,然后将所有整数加在一起

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7107408/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 18:39:06  来源:igfitidea点击:

Java, converting string to integers then add all the integers together

java

提问by Matt

I need to add 8 numbers together from a string.E.g. If someone enters say 1234 it will add the numbers together 1 + 2 + 3 + 4 = 10 then 1 + 1 = 2. I have done this so far. I cannot figure out how to add these numbers up using a for loop.

我需要从一个字符串中将 8 个数字相加。例如,如果有人输入说 1234,它将把这些数字相加 1 + 2 + 3 + 4 = 10 然后 1 + 1 = 2。到目前为止我已经这样做了。我无法弄清楚如何使用 for 循环将这些数字相加。

String num2;     
String num3;   
num2 = (jTextField1.getText());
num3 = num2.replaceAll("[/:.,-0]", "");

String[] result = num3.split("");

int inte = Integer.parseInt(num3);

for (int i = 0; i < 8; i++){

// Stuck

}

回答by MByD

How about that (I skipped exceptions...):

怎么样(我跳过了例外......):

String[] sNums = jTextField1.getText().replaceAll("[^1-9]", "").split("(?<!^)");
int sum = 0;
for (String s : sNums) {
    sum += Integer.parseInt(s); // add all digits
}

while (sum > 9) { // add all digits of the number, until left with one-digit number
    int temp = 0;
    while (sum > 0) {
        temp += sum % 10;
        sum = sum / 10;
    }
    sum = temp;
}

回答by helpermethod

For every element in result, you need to convert it to an int, then add it to some variable, maybe called sum.

对于结果中的每个元素,您需要将其转换为 int,然后将其添加到某个变量中,可能称为 sum。

int sum = 0;

// for every String in the result array
for (int i = 0; i < BOUND; i++) { 
  // convert s[i] to int value
  // add the int value to sum
}

回答by Ingo

This pseudo code should do it without splitting, arrays etc.

这个伪代码应该在没有拆分、数组等的情况下完成。

String s = "1234.56";
int sum = 0;
int i = 0;
while (i < s.length()) {
    char c = s.charAt(i)
    if (c >= '0' && c <= '9') sum += c - '0';
    i++;
}

Should result in sum = 21

应该导致总和 = 21

回答by Dorus

public static int addAll(String str) {
    str = str.replaceAll("[^1-9]", "");
    if (str.length() == 0)
        return 0;
    char[] c = str.toCharArray();
    Integer result = c[0] - 48;
    while (c.length > 1) {
        result = 0;
        for (int i = 0; i < c.length; i++) {
            result += c[i] - 48;
        }
        c = result.toString().toCharArray();
    }
    return result;
}