I am working on a challenge that requires us to input a string containing numbers. For example, "This 23 string has 738 numbers"
And the method needs to add the values of 2+3 to return 5 and 7+3+8 to return 18.
But I don't know how to make a loop to find each number in the input string, perform that operation, and continue through the rest of the string. Any suggestions or solutions?
A successful method would take a string as an input, like "This 23 string has 34 or cat 48", and the method would return 5, 7 and 12.
I have figured out how to use regular expressions to tease out the numbers from a string, but I don't know how to add the digits of each number teased out into an output
package reverseTest;
import java.util.Scanner;
public class ExtractNumbers {`enter code here`
public static void main(String[] args)
{
String str;
String numbers;
Scanner SC=new Scanner(System.in);
System.out.print("Enter string that contains numbers: ");
str=SC.nextLine();
//extracting string
numbers=str.replaceAll("[^0-9]", "");
System.out.println("Numbers are: " + numbers);
}
}
And this adds ALL the numbers in a string:
String a="jklmn489pjro635ops";
int sum = 0;
String num = "";
for(int i = 0; i < a.length(); i++) {
if(Character.isDigit(a.charAt(i))) {
num = num + a.charAt(i);
} else {
if(!num.equals("")) {
sum = sum + Integer.parseInt(num);
num = "";
}
}
}
System.out.println(sum);
}
I don't know how to combine this code with code that can add the numbers this method outputs together.
