In: Computer Science
Write a program the declares and uses two parallel arrays. One array for storing the names of countries and a second array for storing the populations of those countries. As you can see per the following the Country name and it's corresponding Population are stored at the same element index in each array.
China | 1367960000 |
India | 1262670000 |
United States | 319111000 |
Indonesia | 252164800 |
Brazil | 203462000 |
Pakistan | 188172000 |
Nigeria | 178517000 |
Bangladesh | 157339000 |
Russia | 146149200 |
Japan | 127090000 |
In the main method write a loop which asks the user if they would like to look up a given country's population.
Implementation in JAVA:
code:
import java.util.Scanner;
public class Country_Population {
public static void main(String[] args) {
// create scanner class object
Scanner s= new
Scanner(System.in);
// declare and initialize country
and population array of type long and String
String country[]=
{"China","India","United_States","Indonesia","Brazil","Pakistan","Nigeria","Bangladesh","Russia","Japan"};
long pop[]=
{1367960000,1262670000,319111000,252164800,203462000,188172000,178517000,157339000,146149200,127090000};
System.out.print("\nDo you want to
search population for country : ");
// user ask for continue
String ans=s.next();
s.nextLine();
// if invalid inout
if(!(ans.equals("Yes") ||
ans.equals("No"))){
System.out.print("Invalid Input Re-enter Please - ");
ans=s.next();
}
// loop untill user enter yes for
continuition
while(ans.equals("Yes")) {
System.out.print("Enter country name : ");
// ask user for country
anme
String
con=s.next();
s.nextLine();
// get population
long popu=
getpop(country,pop,con);
// print
population
if(popu!=-1) {
System.out.println("Population in "+con+" is : "+popu);
}
else {
System.out.println("Sorry! Country not found!!!");
}
System.out.print("\nDo
you want to continue : ");
// again ask for
continuition
ans=s.next();
s.nextLine();
if(ans.equals("No"))
{
System.out.println("Program Terminated \nThank you!!!");
return;
}
// for invalid
input
if(!(ans.equals("Yes")
|| ans.equals("No"))){
System.out.print("Invalid Input Re-enter Please
- ");
ans=s.next();
}
}
}
// method will return population if found for cname'th
index in pop array
// else return -1 if not found
public static long getpop(String[] country, long
pop[],String cname ) {
for(int
i=0;i<country.length;i++) {
if(cname.equals(country[i])) {
return pop[i];
}
}
return -1;
}
}
SAMPLE OUTPUT:
// PLEASE THUMBS-UP AND RATE POSITIVELY
If you have any doubt regarding this question please ask me in
commnets
// THANK YOU:-)