Menu
Question Index
...

What will be the output of the following program?

import java.util.*;
public class CityDistances {
    static List<City> cities = new ArrayList<City>();
    public static void main(String[] args) {
        cities.add(new City("Delhi", 15, 15));
        cities.add(new City("Mumbai", 5, 50));
        cities.add(new City("Kolkata", 25, 50));
        cities.add(new City("Chennai", 25, 80));
        cities.add(new City("Bangalore", 15, 70));
        printDistance("Delhi", "Mumbai");
        printDistance("Delhi", "Hyderabad");
        printDistance("Kolkata", "Chennai");
        printDistance("Kolkata", "Bangalore");
        printDistance("Hyderabad", "Bangalore");
    }
    private static void printDistance(String name1, String name2) {
        City first = null, second = null;
        for (City city : cities) {
            if (city.equals(name1)) { first = city; }
            if (city.equals(name2)) { second = city; }
        }
        if (first != null && second != null && first != second) {
            int distance = (int) Math.sqrt((first.x - second.x) * (first.x - second.x) + (first.y - second.y) * (first.y - second.y));
            System.out.print(first.name.charAt(0) + "->" + second.name.charAt(1) + "=" + distance + ",");
        } else {
            System.out.print("NA,");
        }
    }
}
class City {
    int x; int y; String name;
    public City(String name, int x, int y) {
        this.x = x; this.y = y; this.name = name;
    }
}


D->M=14,NA,K->C=0,K->B=14,NA,
D->M=36,NA,K->C=30,K->B=22,NA,
D->u=36,NA,K->h=30,K->a=22,NA,
Some other output or Compilation Error or Runtime Error

Doubts

Problems

Topic: Java ArrayList

Read this topic
Take test on this topic

0
Wrong
Score more than 2 points

© meritcampus 2019

All Rights Reserved.

Open In App