I am wanting to print the following output: Itinerary: NEW YORK to FRANCE to ITALY to ATLANTA to SALT LAKE CITY.
Please note that my program will prompt you for a series of destinations. The user will enter those destinations and then it will display your travel route based on your entries. I am new to java so I apologize in advance if my code is written odd. But here is my current work:
StringBuilder sb = new StringBuilder();
static Scanner input = new Scanner(System.in);
static ArrayList<String> destinations = new ArrayList<String>();
public static void main(String[] args)
{
System.out.println("This program will prompt you for a series of destinations.\n"
+ "Then it will display your travel route based on your entries.");
System.out.println("Please enter your destinations [Enter done to finish]:");
System.out.println("Destination: ");
String in = input.nextLine().toUpperCase();
while (!"done".equalsIgnoreCase(in))
{
destinations.add(in);
System.out.println("Destination: ");
in = input.nextLine().toUpperCase();
}
// for each loop
for (String destinations : destinations) {
//The User typed Done.
System.out.print("Itinerary: "+ destinations);
}
}
}
This is my current output:
This program will prompt you for a series of destinations.
Then it will display your travel route based on your entries.
Please enter your destinations [Enter done to finish]:
Destination:
Hawaii
Destination:
New York
Destination:
Chicago
Destination:
done
Itinerary: HAWAIIItinerary: NEW YORKItinerary: CHICAGO
Any insight you can kindly provide would be greatly appreciated.
>Solution :
The problem lies in how you output the destinations in the end – as the "Itinerary: " part is printed out inside the loop, it’s printed out repeatedly. What you’d need to do is print "Itinerary: " before and then go through the destinations:
System.out.print("Itinerary: ");
for(int i=0;i<destinations.size();i++){
System.out.print(destinations.get(i));
if(i!=destinations.size()-1) System.out.print(" to ");
}
System.out.print(".");
Note that I didn’t use for(String s : destinations) in order to be able to check if the String currently being printed is the last one.