I need to create a java program that takes a string array of countries and prints out the name of countries and how many times they are in the in the array.
Example:
String[] countries = {"Mexico","Russia","USA","Russia","Mexico",
"USA","Germany", "Mexico", "Canada" };
I need the output to be:
Mexico 3
Russia 2
USA 2
Germany 1
Canada 1
Here is what i have so far:
public class TestingTwo {
public static void main (String args[]) {
String[] countries = {"Mexico","Russia","USA", "Russia","Mexico", "USA","Germany", "Mexico", "Canada" };
int i;
int j;
for(i=0;i<countries.length-1;i++) {
int count=0;
for(j=i+1;j<countries.length;j++) {
if ((countries[i]==countries[j]) && (i != j)) {
count++;
System.out.println(countries[j]+ " " + count);
}
}
}
}//end of main method
}//end of class
The output im getting is:
Mexico 1
Mexico 2
Russia 1
USA 1
Mexico 1
Issue Faced : I am having trouble finding a way to print out the country name only once. I am able get it to where it prints the countries that have duplicates, but it prints it several times. I am also having trouble with int count and how to get calibrate correctly to the amount of duplicates.