Write a program that does the following: Create an ArrayList of Strings and call
ID: 3886125 • Letter: W
Question
Write a program that does the following:
Create an ArrayList of Strings and call it itinerary
Read in destinations from the user until the user enters done (or DONE,
or dOnE, .. ) As you read in the destinations add them to the itinerary
Next You need to create a String called travelRoute that includes the travel
route as shown in the output
Use a StringBuilder called sb to create the String travelRoute .
Loop through all the elements of the ArrayList itinerary
Change the destinations (e.g. Rome) to all uppercase letters (e.g. ROME) before adding them to sb
Add the word to (lowercase) between the destinations, but not at the end)
When you are done create the string travelRoute based on the information stored in sb.
Print the String travelRoute.
Sample Output:
Explanation / Answer
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Travel {
/**
* @param args
*/
public static void main(String[] args) {
// ArrayList of Strings and call it itinerary
List<String> itinerary = new ArrayList<String>();
Scanner scanner = null;
try {
scanner = new Scanner(System.in);
String destination = "";
// Read in destinations from the user until the user enters done
do {
System.out.print("Destination: ");
destination = scanner.next();
if (destination.equals("Done")||destination.equals("DOnE")||destination.equals("DONE"))
break;
else
// destinations add them to the itinerary
itinerary.add(destination);
} while (true);
// StringBuilder called sb to create the String travelRoute
StringBuilder sb = new StringBuilder();
// Loop through all the elements of the ArrayList itinerary
for (int i = 0; i < itinerary.size(); i++) {
String dest = itinerary.get(i);
if (i == itinerary.size() - 1)
sb.append(dest.toUpperCase());
else {
sb.append(dest.toUpperCase() + " to ");
}
}
// create the string travelRoute based on the information stored in
// sb.
String travelRoute = sb.toString();
// Print the String travelRoute.
System.out.println("travel route: " + sb);
} catch (Exception e) {
// TODO: handle exception
}
}
}
OUTPUT:
Destination: London
Destination: Paris
Destination: Rome
Destination: done
travel route:
LONDON to PARIS to ROME
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.