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 | 3
0 |1135 | 1016 | 2015
1 | 807 | 1250 | 2128
2 | 174 | 1240 | 2121
Ask user to enter 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 Main {
public static void main(String[] args) {
ArrayList<String> fromCity = new ArrayList<>();
fromCity.add("Los Angeles");
fromCity.add("San Francisco");
fromCity.add("Portland");
ArrayList<String> toCity = new ArrayList<>();
toCity.add("Seattle");
toCity.add("Denver");
toCity.add("Chicago");
int[][] distance = {{1135, 1016, 2015}, {807, 250, 2128}, {174, 1240, 2121}};
Scanner in = new Scanner(System.in);
System.out.println("Enter the name of city to “travel from”:");
String from = in.nextLine();
int i = fromCity.indexOf(from);
System.out.println("Enter the name of city to “travel to”:");
String to = in.nextLine();
int j = toCity.indexOf(to);
System.out.println("Distance is " + distance[i][j]);
}
}
Comments
Leave a comment