In: Computer Science
Write a java program that will take a line of input and go
through and print out that line again with all
the word numbers swapped with their corresponding numeric
representations (only deal with numbers
from one to nine). Sample runs might look like this:
Please enter a line of input to process:
My four Grandparents had five grandchildren
My 4 grandparents had 5 grandchildren
without array and methods.
Below is your code:
import java.util.Scanner;
public class StringReplace {
public static void main(String[] args) {
// initializing Scanner object to get input from user
Scanner sc = new Scanner(System.in);
// Prompt user to take input from user
System.out.println("Please enter a line of input to process:");
// take complete line as input
String line = sc.nextLine();
// closing the scanner after taking input
sc.close();
// string has a replaceAll method which can replace
// any substring to another substring
// we can use the same for that
// also if we add (?i) in front of the substring to be replaced
// it will consider as case insensitive
line = line.replaceAll("(?i)one", "1");
line = line.replaceAll("(?i)two", "2");
line = line.replaceAll("(?i)three", "3");
line = line.replaceAll("(?i)four", "4");
line = line.replaceAll("(?i)five", "5");
line = line.replaceAll("(?i)six", "6");
line = line.replaceAll("(?i)seven", "7");
line = line.replaceAll("(?i)eight", "8");
line = line.replaceAll("(?i)nine", "9");
// printing the result
System.out.println(line);
}
}
Output
Please enter a line of input to process:
My four Grandparents had five grandchildren
My 4 Grandparents had 5 grandchildren