I'm trying to make all the strings that contains a capital letter from the input text file to appear in green color in the output console. E.g., input text file contains "I'm used to speak in English." the output should be the whole sentence from the input text file "I'm used to speak in English." with the strings "I'm" and "English" displayed in green color. But I only manage to display the strings "I'm" and "English" in green color without displaying the whole sentence on the console.
Can anyone help to solve this? My code:
public static void main(String[] args) throws FileNotFoundException {
Scanner sc = new Scanner(new File("Testing.txt"));
while(sc.hasNext()){
String line = sc.nextLine();
String arr [] = line.split(" ");
StringBuilder out = new StringBuilder();
for (int i = 0; i < arr.length; i++) {
if (Character.isUpperCase(arr[i].charAt(0))) {
out.append(arr[i]);
}
}
if (out.length() > 1) {
out.setLength(out.length() -2);
}
System.out.println ("\u001B[32m " + out);
}
}
Try out something like this:
public static void main(String[] args) throws FileNotFoundException {
Scanner sc = new Scanner(new File("Testing.txt"));
while(sc.hasNext()){
String line = sc.nextLine();
String arr [] = line.split(" ");
StringBuilder out = new StringBuilder();
for (int i = 0; i < arr.length; i++) {
if (Character.isUpperCase(arr[i].charAt(0))) {
out.append("\u001B[32m").append(arr[i]).append(" ");
} else {
out.append("\u001b[0m").append(arr[i]).append(" ");
}
}
System.out.println (out);
}
}
The idea is to store not only the words with the first uppercase letter, but all the words and use \u001b[0m
escape sequence to reset formatting for the other words.