In: Computer Science
City 1 |
1 |
1 |
City 2 |
1 |
3 |
City 3 |
4 |
1 |
City 4 |
5 |
3 |
City 5 |
3 |
5 |
in java Create 5 city objects and initialize their location (x and y) using the above table. Then put all of the five cities in a vector.
code:
import java.util.*;
class City {//creating a class
String name;
int x,y;
City(String name,int x,int y)//constructor to
intitialise variables
{
this.name=name;
this.x=x;
this.y=y;
}
}
class Vector_Example {
public static void main(String[] args)
{
Vector v = new Vector();//creating
a vector
Scanner sc=new
Scanner(System.in);//scannwe class to read input
for(int i=0;i<5;i++)
{
System.out.println("Enter name, x,y:");
String
name=sc.next();
int
x=sc.nextInt();
int
y=sc.nextInt();
City c=new
City(name,x,y);//creating a city object
v.add(c);//adding it to vector
}
System.out.println("The Objects in
Vector are");
for(int i=0;i<5;i++)
{
City c
=(City)v.get(i);//obtaining the object
System.out.println(c.name+" "+c.x+" "+c.y);
}
}
}
output: