I want to add numbers using Java.
For example, the sentence is given String: "My age is 50, and your age is under 30." If I want to add 5 to the sentence, it should be like "My age is 55, and your age is under 35."
The restriction is the sentence is given, so you need to extract numbers from the sentence and add the numbers to the original sentence.
I was trying to split by space (" ") and try to add numbers after that. But I don't know how to substitute numbers with the original sentence.
I am confused since it has comma when I am trying to split by " " and even if you can extract all the numbers from the sentence, I am not sure how can I get back to numbers to string.
public class Main {
public static Pattern pattern = Pattern.compile("\\d+");
public static String addNumber(String str, int n) {
Matcher matcher = pattern.matcher(str);
if (matcher.find()) {
String theAge = matcher.group(0);
int newAge = Integer.parseInt(theAge) + n;
}
String addSentence = str;
return addSentence;
}
public static void main(String[] args) {
String testString = "My age is 50, and your age is under 30.";
String testString2 = "My age is 50, and your age is under 30 and my friend age is 44.";
String newSent = addNumber(testString, 5);
// -> should be "My age is 55, and your age is under 35.
String newSent2 = addNumber(testString2, 10);
// -> should be "My age is 60, and your age is under 40 and my friend age is 54.";
}
} enter code here