- You need a loop to continue the execution until the user inputs
EXIT
. - You can match and replace an integer using a regex.
Demo:
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main {
public static void main(String[] args) {
Scanner kbReader = new Scanner(System.in);
String userIn;
Pattern pattern = Pattern.compile("\\b\\d+\\b");// String of one or more digits bounded by word-boundary
while (true) {
System.out.print("Please type in a sentence, or type EXIT to end the program: ");
userIn = kbReader.nextLine();
if ("EXIT".equalsIgnoreCase(userIn)) {
break;
}
StringBuilder sb = new StringBuilder();
Matcher matcher = pattern.matcher(userIn);
int lastProcessedIndex = 0;
while (matcher.find()) {
String number = matcher.group();
int startIndex = matcher.start();
// Append the string starting from the last processed index and then append the
// doubled integer
sb.append(userIn.substring(lastProcessedIndex, startIndex))
.append(String.valueOf(2 * Integer.parseInt(number)));
// Update the last processed index
lastProcessedIndex = startIndex + number.length();
}
// Append the remaining substring
sb.append(userIn.substring(lastProcessedIndex));
System.out.println("The updated string: " + sb);
}
}
}
A sample run:
Please type in a sentence, or type EXIT to end the program: hello 10 world 5 how are 15 doing?
The updated string: hello 20 world 10 how are 30 doing?
Please type in a sentence, or type EXIT to end the program: exit
CLICK HERE to find out more related problems solutions.