简体   繁体   English

返回所有整数的和

[英]return the sum of all integers

Program should return sum of all the numbers in a string. 程序应以字符串形式返回所有数字的总和。

public static void main(String[] args) {
    String data = "1a2b-3c";
    data=data.replaceAll("[\\D]+"," ");
    String[] numbers=data.split(" ");
    int sum = 0;
    for(int i=0;i<numbers.length;i++){
        try{
            sum+=Integer.parseInt(numbers[i]);
        }
        catch( Exception e ) {
          e.printStackTrace();
        }
    }
    System.out.println("The sum is:"+sum);

}

So for the above input, it should return sum as 0 ==> (1+2 - 3) 因此,对于上述输入,它应返回和为0 ==> (1+2 - 3)

But my above code returns 6. What is the right regex for this? 但是我上面的代码返回6。什么是正确的正则表达式呢?

Here's how you should do it 这是你应该怎么做的

String data = "1a2b-3c";
int sum=0;
Pattern p = Pattern.compile("-?\\d+");
Matcher m = p.matcher(data);
while (m.find()) {
  sum+=Integer.parseInt(m.group());
}

A simple way would be to do this. 一个简单的方法就是这样做。

 if(numbers[i - 1].equals('-')){
           sum-=Integer.parseInt(numbers[i]);
 } else 
   sum+=Integer.parseInt(numbers[i]);

Use the split tool on your String, splitting every symbol individually into an array , then just add the numbers with parseInt and you're done. 使用字符串上的拆分工具,将每个符号分别拆分为一个数组,然后将其与parseInt相加即可。 No need for a pattern here I think. 我认为这里不需要模式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM