Java 从阵列打印信息,而不使用重复值

Java 从阵列打印信息,而不使用重复值,java,arrays,Java,Arrays,我正在编写一个程序,接收奥运会奖牌数据,并打印出各种信息。这一部分在逻辑和结构上有点困难。我试图获取一个字符串数组和一个int数组(都是在main方法中创建的),将它们传递给一个新方法,并打印出有关它们的信息 我的数组如下(请注意字符串数组按字母顺序排列): 我想打印如下: Afghanistan, 3 medal(s) Canada, 1 medal(s) China, 1 medal(s) Italy, 3 medal(s) Mexico, 2 medal(s) 我可以很容易地编写以这种格

我正在编写一个程序,接收奥运会奖牌数据,并打印出各种信息。这一部分在逻辑和结构上有点困难。我试图获取一个
字符串数组
和一个
int数组
(都是在main方法中创建的),将它们传递给一个新方法,并打印出有关它们的信息

我的数组如下(请注意字符串数组按字母顺序排列):

我想打印如下:

Afghanistan, 3 medal(s)
Canada, 1 medal(s)
China, 1 medal(s)
Italy, 3 medal(s)
Mexico, 2 medal(s)
我可以很容易地编写以这种格式列出的程序,但是多次出现的国家(在这个示例中…阿富汗)在数组中列出的次数与它在数组中出现的次数相同。如前所述,我的输出是:

Afghanistan, 1 medal(s)
Afghanistan, 2 medal(s)
Canada, 1 medal(s)
China, 1 medal(s)
Italy, 3 medal(s)
Mexico, 2 medal(s)
阿富汗被列为两个国家(为了提供一个大的背景,这是该计划的一个小部分。该计划实际上也有运动员的名字,但有不同的方法处理)

有谁能为我提供一些帮助,告诉我打印所需输出的最佳方法吗

import java.util.*;
import java.io.*;

public class Project {

public static void main(String[] args) {
    String[] country = {"Afghanistan", "Afghanistan", "Canada", "China", "Italy", "Mexico"};
    int[] totalMedals = {1, 2, 1, 1, 3, 2};

    listCountryMedals(country, totalMedals);

}

    //List the grand total of medals for each country...display name only once
public static void listCountryMedals(String[] country, int[] totalMedals) {

    for (int i = 0; i < country.length; i++) {
        System.out.println(country[i] + ", " + totalMedals[i] + " medal(s)");            
    }
}
import java.util.*;
导入java.io.*;
公共类项目{
公共静态void main(字符串[]args){
字符串[]国家={“阿富汗”、“阿富汗”、“加拿大”、“中国”、“意大利”、“墨西哥”};
int[]TotalAcadems={1,2,1,1,3,2};
ListCountry奖牌(国家,奖牌总数);
}
//列出每个国家的奖牌总数…仅显示一次名称
公共静态无效列表国家奖牌(字符串[]国家,整数[]总奖牌){
对于(int i=0;i
如下更改您的方法

public static void listCountryMedals(String[] country, int[] totalMedals) {

     //Map to hold the conuntry anme and medal count pair
     Map<String,Integer> countryNameToMedalCountMap= new HashMap<String,Integer>();

      for (int i = 0; i < country.length; i++) {           
         if(countryNameToMedalCountMap.get(country[i]) == null) {
             countryNameToMedalCountMap.put(country[i],totalMedals[i]);
         } else {
             int count = map.get(country[i]);
             countryNameToMedalCountMap.put(country[i],count+totalMedals[i];
        }
     }

      //Print the map
      for(String counrty : countryNameToMedalCountMap.keySet()) {
          System.out.println(country+" "+ countryNameToMedalCountMap.get(country)+" medal(s).");
      }
}
publicstaticvoidlistCountryCoards(字符串[]国家,整数[]总奖牌){
//持有国家和奖牌计数对的地图
Map countryNameToMedalCountMap=新HashMap();
对于(int i=0;i

注意:使用这种方法,国家名称将区分大小写。如果希望不区分大小写,则必须设置一些机制。如将地图键始终转换为小写,并在查找时执行相同操作,则应采用面向对象的方法:

public class Country {

    private String name;
    private int medals;

    //getters/setters/constructors

}
然后就变得容易了:

List<Country> countries = new ArrayList<>();

//when you want to reference/print those:
for (Country c : countries) {
    System.out.println(String.format("%s, %d medals(s)", c.getName(), c.getMedals()));
}
List countries=new ArrayList();
//当您想要引用/打印这些内容时:
适用于(c国:国家){
System.out.println(String.format(“%s,%d个奖牌)”,c.getName(),c.getaclements());
}
试试这个

public static void listCountryMedals(String[] country, int[] totalMedals)
    {
        Map<String, Integer> countryMap = new HashMap<String, Integer>();

        for (int i = 0; i < country.length; i++)
        {
            Integer medals = countryMap.get(country[i]);
            Integer sum = (medals == null) ? totalMedals[i] : (totalMedals[i] + medals);
            countryMap.put(country[i], sum);
        }

        for (Map.Entry<String, Integer> countryMedals : countryMap.entrySet())
        {
            System.out.println(countryMedals.getKey() + ", " + countryMedals.getValue() + " medal(s)");
        }
    }
publicstaticvoidlistCountryCoards(字符串[]国家,整数[]总奖牌)
{
Map countryMap=newhashmap();
对于(int i=0;i
假设您只想使用数组和循环,可以执行以下操作:

public static void listCountryMedals(String[] country, int[] totalMedals) {
  boolean[]seen = new boolean[country.length];
  for (int i = 0; i < country.length - 1; i++) {
      int medals = totalMedals[i];
      if (!seen[i]) {
          for(int j = i + 1; j < country.length; j++) {
             if (country[i].equals(country[j])) {
                 medals += totalMedals[j];
                 seen[j] = true; //I already took this country
             }
          }
          System.out.println(country[i] + ", " + medals + " medal(s)");
      }
      seen[i] = true;
  }
}
publicstaticvoidlistCountryCoards(字符串[]国家,整数[]总奖牌){
boolean[]seen=新的boolean[country.length];
对于(int i=0;i
我会使用
LinkedHashMap
按国家对奖牌进行汇总:

//List the grand total of medals for each country...display name only once
public static void listCountryMedals(String[] country, int[] totalMedals) {
    final Map<String, Integer> map = new LinkedHashMap<String, Integer>();


    for (int i = 0; i < country.length; i++) {
        if (!map.containsKey(country[i]))
            map.put(country[i], 0);
        map.put(country[i], map.get(country[i]) + totalMedals[i]); 
    }

    for (final Entry<String, Integer> entry : map.entrySet()) {
        System.out.println(entry.getKey() + ", " + entry.getValue() + " medal(s)");           
    }
}
//列出每个国家的奖牌总数…只显示一次名称
公共静态无效列表国家奖牌(字符串[]国家,整数[]总奖牌){
最终映射=新LinkedHashMap();
对于(int i=0;i

与经典的
HashMap
相反,
LinkedHashMap
在迭代时将保留密钥顺序。似乎您的国家/地区当前已排序,因此您可能希望在打印它们时保持此顺序。

您可以使用map存储这些信息,国家/地区作为密钥,奖牌计数作为值

public static void listCountryMedals(String[] country, int[] totalMedals) 
{
    Map<String, Integer> countryMedalMap = new LinkedHashMap<String, Integer>();
    for (int i = 0; i < country.length; i++) 
    {
        String countryName = country[i];
        /**
         * If the country is already in the map, get the number of medal and add it up with value 
         * from totalMedals array for that country. Then put it back to map with the new medal count.
         */
        if(countryMedalMap.containsKey(countryName))
        {
            int medalCount = countryMedalMap.get(countryName) + totalMedals[i];
            countryMedalMap.put(countryName, medalCount);
        }
        /**
         * If the country is not in the map, put it into map with its medal count.
         */
        else
        {
            countryMedalMap.put(countryName, totalMedals[i]);
        }
    }

    printMap(countryMedalMap);
}

/**
 * Print the map
 * 
 * @param map
 */
public static void printMap(Map<String, Integer> map)
{
    for (String countryName : map.keySet())
    {
        System.out.println(String.format("%s, %s medal(s)", countryName, map.get(countryName)));
    }
}
publicstaticvoidlistCountryCoards(字符串[]国家,整数[]总奖牌)
{
Map countryMedalMap=newlinkedhashmap();
对于(int i=0;ipublic static void listCountryMedals(String[] country, int[] totalMedals) 
{
    Map<String, Integer> countryMedalMap = new LinkedHashMap<String, Integer>();
    for (int i = 0; i < country.length; i++) 
    {
        String countryName = country[i];
        /**
         * If the country is already in the map, get the number of medal and add it up with value 
         * from totalMedals array for that country. Then put it back to map with the new medal count.
         */
        if(countryMedalMap.containsKey(countryName))
        {
            int medalCount = countryMedalMap.get(countryName) + totalMedals[i];
            countryMedalMap.put(countryName, medalCount);
        }
        /**
         * If the country is not in the map, put it into map with its medal count.
         */
        else
        {
            countryMedalMap.put(countryName, totalMedals[i]);
        }
    }

    printMap(countryMedalMap);
}

/**
 * Print the map
 * 
 * @param map
 */
public static void printMap(Map<String, Integer> map)
{
    for (String countryName : map.keySet())
    {
        System.out.println(String.format("%s, %s medal(s)", countryName, map.get(countryName)));
    }
}