Create a Java ArrayList of String type “fromCity”, use “Add()” method to add three elements: “Los Angeles”, “San Francisco”, and “Portland”. Create another Java ArrayList of String type “toCity” with three elements: “Seattle”, “Denver”, and “Chicago”. Make two-dimensional array of int type named “distance” whose elements are from table. Be sure to make the elements using the index of [from][to].
4x4 Table:
fromCity \ toCity | 0 | 1 | 2
0 | 1135 | 1016 | 2015
1 | 807 | 1250 | 2128
2 | 174 | 1240 | 2121
Ask user to enter the name of city to “travel from”, use “indexof()” method to find the index of the given city in the “fromCity” ArrayList.
Ask user to enter the name of city to “travel to”, then use“indexOf()” method to find the index of the given city in the “toCity” ArrayList. Find “distance” array and display it.
import java.util.ArrayList;
import java.util.Scanner;
public class Distance {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String cityFrom = " ";
String cityTo = " ";
ArrayList<String> fromCity = new ArrayList<String>();
fromCity.add("Los Angeles");
fromCity.add("San Francisco");
fromCity.add("Portland");
System.out.println("From city:");
for (String city : fromCity) {
System.out.println(city);
}
ArrayList<String> toCity = new ArrayList<String>();
toCity.add("Seattle");
toCity.add("Denver");
toCity.add("Chicago");
System.out.println("");
System.out.println("To city:");
for (String city : toCity) {
System.out.println(city);
}
System.out.println("Please provide name of city from were you goes and press Enter: ");
cityFrom = scan.nextLine();
System.out.println("Index choosen city:");
System.out.println(fromCity.indexOf(cityFrom));
System.out.println("Please provide name of city arriving to and press Enter: ");
cityTo = scan.nextLine();
System.out.println("Index choosen city:");
System.out.println(toCity.indexOf(cityTo));
int[][] distance = { { 1135, 1016, 2015 }, { 807, 1250, 2128 }, { 174, 1240, 2121 } };
System.out.println("4x4 Table:");
System.out.println("fromCity\\toCity");
System.out.println(" | 0 | 1 | 2");
for (int i = 0; i < distance.length; i++) {
for (int j = 0; j < distance.length; j++) {
System.out.print(i + "|");
System.out.printf("%4d", distance[i][j]);
System.out.print(" ");
}
System.out.println();
}
scan.close();
}
}
Comments
Leave a comment