MichiganCitiesTester class Here is what I am asked to do for the askForRoute met
ID: 3538748 • Letter: M
Question
MichiganCitiesTester class
Here is what I am asked to do for the askForRoute method
askForRoute method : Ask to user for a route.
User has to enter a route (cities separated by - ) like this... (kalamazoo-detroit-grandRapids). This method has to do a validation: all cities MUST exist in the cities array. Repeat until user
enters a valid route (valid route = all cities have to exist in the cities array). This method returns a valid route (route
is a String array)
this is what I have, I think i have the validation working, I just don't know how to split the input up and put it into a string array to return it?
private static String[] askForRoute(MichiganCities myInfo) {
Scanner in = new Scanner(System.in);
MichiganCities test = new MichiganCities();
java.util.ArrayList route = new java.util.ArrayList();
String rte, token;
int index = 0;
do
{
route.clear();
System.out.print(" Enter your route by using - as delimiter like this: kalamazoo-grandrapids-lansing ");
System.out.print(" ");
rte = in.next();
}
Help Here please!
for (int i = 0; i < route.size(); i++)
{
index = test.findIndexCity(route.get(i));
if (index < 0)
{
System.out.print("Route with some invalid city. Try again");
System.out.print(" ");
break;
}
}
}while (index < 0);
}
Explanation / Answer
// just use the string.split() method
// implemented below
private static String[] askForRoute(MichiganCities myInfo) {
Scanner in = new Scanner(System.in);
MichiganCities test = new MichiganCities();
java.util.ArrayList route = new java.util.ArrayList();
String rte, token;
int index = 0;
do
{
route.clear();
System.out.print(" Enter your route by using - as delimiter like this: kalamazoo-grandrapids-lansing ");
System.out.print(" ");
rte = in.next();
}
// first split on '-'
String cities[] = rte.split("-");
// then add string array to arrayList route
java.util.Collections.addAll(route, cities);
for (int i = 0; i < route.size(); i++)
{
index = test.findIndexCity(route.get(i));
if (index < 0)
{
System.out.print("Route with some invalid city. Try again");
System.out.print(" ");
break;
}
}
}while (index < 0);
}