These are explanatory comments on the modifyLine method :
public static String modifyLine(String line){
// the word variable stores each word in the line : the string produced until we meed a non-alphanumerical character
StringBuilder word = new StringBuilder();
// the result variable stores the new version of the line
StringBuilder result = new StringBuilder();
for(char c : line.toCharArray()){
// if the character is neither an alphabet or a digit
if(! (Character.isAlphabetic(c) || Character.isDigit(c))){
// if the current word is numerical then check whether we should replace it or not
if(isNumerical(word.toString())){
int i = Integer.parseInt(word.toString());
// if ( i>=0 && i<=12)
if(map.containsKey(i))
result.append(map.get(i));
else
result.append(word);
}
// if the current word is not numerical then we just need to append it to the result var
else{
result.append(word);
}
// either way we need to append the non-alphanumerical character to the result var
result.append(c);
// reset the word var
word = new StringBuilder();
}
else{
//add the read character to the current word
word.append(c);
}
}
return result.toString();
}
package com.codegym.task.task19.task1924;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;
/*
Replacing numbers
*/
public class Solution {
public static Map<Integer, String> map = new HashMap<>();
static {
map.put(0,"zero");
map.put(1,"one");
map.put(2,"two");
map.put(3,"three");
map.put(4,"four");
map.put(5,"five");
map.put(6,"six");
map.put(7,"seven");
map.put(8,"eight");
map.put(9, "nine");
map.put(10,"ten");
map.put(11,"eleven");
map.put(12,"twelve");
}
public static void main(String[] args) throws IOException {
BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
String fileName= input.readLine();
input.close();
replace(fileName);
}
public static void replace(String fileName) throws IOException {
FileReader r = new FileReader(fileName);
BufferedReader reader = new BufferedReader(r);
String line;
while((line=reader.readLine())!= null){
System.out.println(modifyLine(line));
}
reader.close();
r.close();
}
public static String modifyLine(String line){
StringBuilder word = new StringBuilder();
StringBuilder result = new StringBuilder();
for(char c : line.toCharArray()){
if(! (Character.isAlphabetic(c) || Character.isDigit(c))){
if(isNumerical(word.toString())){
int i = Integer.parseInt(word.toString());
if(map.containsKey(i))
result.append(map.get(i));
else
result.append(word);
}
else{
result.append(word);
}
result.append(c);
word = new StringBuilder();
}
else{
word.append(c);
}
}
return result.toString();
}
public static boolean isNumerical(String line){
boolean test= false;
for(char c : line.toCharArray()){
test = Character.isDigit(c);
if(!test)
break;
}
return test;
}
}