In: Computer Science
Lab Text Manipulation
Inside the main method, do the following:
The output depends on the information provided by the user.
Please enter your favorite National Park or DONE to stop: mesa
verde
Please enter your favorite National Park or DONE to stop: black
CANYON of ThE gunnisON
Please enter your favorite National Park or DONE to stop:
DENALI
Please enter your favorite National Park or DONE to stop:
yellowStone
Please enter your favorite National Park or DONE to stop:
Done
Favorite National Parks: Mesa Verde | Black Canyon Of The Gunnison
| Denali | Yellowstone
Screenshot
Program
import java.util.ArrayList;
import java.util.Scanner;
public class TextManipulator {
public static void main(String[] args) {
//Object to read user input
Scanner sc=new
Scanner(System.in);
//Create an ArrayList of strings
and call it parks
ArrayList<String>parks=new
ArrayList<String>();
//Read in the names of national
parks from the user until the user enters done
String name="";
System.out.print("Please enter your
favorite National Park or DONE to stop: ");
name=sc.nextLine();
while(!name.equalsIgnoreCase("done")) {
parks.add(name);
System.out.print("Please enter your favorite National Park or DONE
to stop: ");
name=sc.nextLine();
}
System.out.println();
//Create Text
StringBuilder nationalParks=new
StringBuilder();
for (int
i=0;i<parks.size()-1;i++)
{
nationalParks.append(parks.get(i));
nationalParks.append(" | ");
}
nationalParks.append(parks.get(parks.size()-1));
//Display Formatted text
System.out.println("\nFavorite
National Parks: "+updateSpelling(nationalParks.toString()));
}
//Method to change first letter of a word into capital
and all others are small
private static String updateSpelling(String text)
{
//For temporary storage
StringBuilder s = new
StringBuilder();
//For check the starting point of a
word
char ch = ' ';
//Loop through each
character of the text
for (int i = 0; i <
text.length(); i++) {
//If a character's previous charcter space and next is a character
then change upeercase
//Because
it is starting letter of a word
if (ch == ' ' && text.charAt(i) != ' ') {
s.append(Character.toUpperCase(text.charAt(i)));
}
//Check other letters and change into lower case
else if(Character.isLetter(text.charAt(i))) {
s.append(Character.toLowerCase(text.charAt(i)));
}
//Other than letters
else {
s.append(text.charAt(i));
}
//Keep track of prev character
ch =text.charAt(i);
}
//Return string
return
s.toString();
}
}
------------------------------------------------------------
Output
Please enter your favorite National Park or DONE to stop: mesa
verde
Please enter your favorite National Park or DONE to stop: black
CANYON of ThE gunnisON
Please enter your favorite National Park or DONE to stop:
DENALI
Please enter your favorite National Park or DONE to stop:
yellowStone
Please enter your favorite National Park or DONE to stop: Done
Favorite National Parks: Mesa Verde | Black Canyon Of The Gunnison
| Denali | Yellowstone