Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
229 views
in Technique[技术] by (71.8m points)

java program to return the sum of all integers found in the parameter String

i want write a java program to return the sum of all integers found in the parameter String. for example take a string like:" 12 hi when 8 and 9" now the answer is 12+8+9=29. but i really dont know even how to start can any one help in this!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You may start with replacing all non-numbers from the string with space, and spilt it based on the space

String str = "12 hi when 8 and 9";
str=str.replaceAll("[\D]+"," ");
String[] numbers=str.split(" ");
int sum = 0;
for(int i=0;i<numbers.length;i++){
    try{
        sum+=Integer.parseInt(numbers[i]);
    }
    catch( Exception e ) {
      //Just in case, the element in the array is not parse-able into Integer, Ignore it
    }
}
System.out.println("The sum is:"+sum);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...