【问题标题】:Olympics java coding奥运会java编码
【发布时间】:2016-10-11 21:24:38
【问题描述】:

我正在编写一个程序,我必须计算每个国家/地区的金牌数。输入将来自一个文件,我必须处理该文件。 第一行是国家代码,第二行是事件类型,第三行是事件。输入是这样的:

CHN 
Diving 
Women's 10m Platform 
CAN 
Rowing 
Men's Eight 
CHN
Rowing
Women's Quadruple Sculls

预期的输出应该是这样的:

Count of gold medallists by country:
CHN - 2
CAN - 1

Count of gold medallists by event type:
Diving - 1
Rowing - 2

好的,所以我创建了一类金牌,它将根据事件类型为每个国家创建一个新的实例对象。我的代码在这里:

class GoldMedals {
  private String country;
  private String eventType;
  private String event;
  private int medalCount;

 public GoldMedals(String name, String type, String event) {
   this.country = name;
   this.eventType = type;
   this.event = event;
   medalCount = 1;
}

public boolean matchDetails(String countryName, String type){
return (country.equals(countryName) && eventType.equals(type));
}

我的主要方法在这里:

try {
  input = new BufferedReader(new FileReader ("textfile.txt"));
  country = input.readLine();
  while(country!=null) {
    eventType = input.readLine();
    event = input.readLine();
    match = findMatch(winners, size, country, eventType);
    if(match == null) {
    winners[size] = new GoldMedals(country, eventType, event);
    size++;
      //match.addMedal();
    } //else {

        //match.addMedal();          
    //}
    //match.addMedal();
    country = input.readLine();
  }

  input.close();
} catch (IOException ioe) {
  System.out.println(ioe.getMessage());

我还添加了一个静态方法,以确保我们不会创建已经存在的对象。 (冗余对象)

public static GoldMedals findMatch(GoldMedals[] winners, int size, String country, String type) {
  GoldMedals result = null;
  int pos;

  pos = 0;
  while (pos < size && result == null) {
    if (winners[pos].matchDetails(country, type)) {
     result = winners[pos];
  } else {
     pos++;
  }
 }
  return result;
}

我想知道的是如何获得所需的输出。因为现在我得到了这个输出

ITA- 1- Fencing- Women's Individual Foil
POL- 1- Rowing- Men's Quadruple Sculls
KEN- 1- Athletics- Men's Marathon 
CHN- 1- Diving- Men's 3m Springboard
TUN- 1- Swimming- Men's 1500m Freestyle
CHN- 1- Canoe/Kayak - Flatwater- Canoe Double (C2) 500m Men
CHN- 1- Diving- Men's Synchronised 3m Springboard 
USA- 1- Gymnastics Artistic- Women's Individual All-Around
RUS- 1- Synchronized Swimming- Duet

这是我编程的。我需要有关如何获得每个国家/地区的总金牌以及根据赛事类型获得金牌的帮助。 简而言之,我怎样才能获得上述所需的输出。 如果您在我的问题上需要帮助,我可以进一步解释。提示将不胜感激。

【问题讨论】:

  • 简单的方法是拥有 2 张地图。第一个以国家/地区之类的字符串作为键,将奖牌数作为值的整数。第二个地图应该有一个事件字符串作为键和一个整数计数器作为值。比循环文件,您将总结国家和事件的奖牌。最后,在 2 个地图上的循环将打印您的输出。
  • 感谢您的回复。问题是我还没有在地图上走得太远(这是我的下一个目标)。为了解决这个问题,我必须学习地图。我想知道的是,如果我不使用地图,我该怎么办。 @MarioAlexandroSantini
  • 如果没有地图,您应该创建一个类 MedalCounter,其中包含 2 个属性、一个名称字符串和一个计数器,而不是创建 2 个 MedalCounter 数组,一份用于国家/地区,一份用于活动。
  • 如此糟糕地循环遍历 GoldMedals 类型的获胜者数组,然后像这样:countryMedalCounter[start] = new MedalCounter(winners[i].country, 1) 我仍然不明白我是否喜欢这样做,它不会将具有不同事件的国家两次.除非我以错误的方式理解您的想法,否则这将破坏整个目的。 @MarioAlexandroSantini

标签: java arrays class object instance


【解决方案1】:

删除medalCount 字段。你的类应该只代表传入的数据。

然后您要构建两个Map&lt;String, Long&gt; 对象,其中键是国家代码或事件类型,值是键的计数。

使用 Java 8 流,这相当简单:

List<GoldMedals> allMedals = loadMedalsFromFile();

Map<String, Long> byCountry = allMedals.stream()
        .collect(Collectors.groupingBy(GoldMedals::getCountry,
                                       Collectors.counting()));

Map<String, Long> byEventType = allMedals.stream()
        .collect(Collectors.groupingBy(GoldMedals::getEventType,
                                       Collectors.counting()));

【讨论】:

  • 感谢您的宝贵时间。正如我回答其他人一样,我对地图不太了解。我需要在没有地图的情况下做到这一点。 (我将为我的下一个项目学习地图)还有其他方法可以解决吗?
  • 你能帮帮我吗?我真的需要一些帮助。从过去 2 小时开始,我一直在自己尝试。
  • 我不知道你有什么或没有学到什么。他们不会给你一个不能用你所学的东西完成的任务,所以你应该能够用你所知道的找到解决方案。再次阅读你的材料。也许这会让你想起一些你没有想到的事情。
  • 我一直在自己编码,但我得到空指针异常。 for (int i = 0; i &lt; size; i++) { String name = winners[i].getCountryName(); if(!name.equals(countryArray[count].getName())) countryArray[count] = new MedalCounter(name, 1); else countryArray[count].updateCount();
  • 我创建了一个名为 MedalCounter 的新类并创建了该类的两个数组实例。我正在遍历 GoldMedal 实例并创建 MedalCounter 的新实例,如果它不存在,否则我只是增加计数器。 MedalCounter 有两个实例变量,分别称为 name 和 counter。
【解决方案2】:

如果您无法使用地图。你可以试试下面的代码:

--金牌

public class GoldMedals {
    private String country;
    private String eventType;
    private String event;
    private int medalCount;

    public GoldMedals(String name, String type, String event) {
        this.country = name;
        this.eventType = type;
        this.event = event;
        medalCount = 1;
    }

    /**
     * @return the country
     */
    public String getCountry() {
        return country;
    }

    /**
     * @param country the country to set
     */
    public void setCountry(String country) {
        this.country = country;
    }

    /**
     * @return the eventType
     */
    public String getEventType() {
        return eventType;
    }

    /**
     * @param eventType the eventType to set
     */
    public void setEventType(String eventType) {
        this.eventType = eventType;
    }

    /**
     * @return the event
     */
    public String getEvent() {
        return event;
    }

    /**
     * @param event the event to set
     */
    public void setEvent(String event) {
        this.event = event;
    }

    /**
     * @return the medalCount
     */
    public int getMedalCount() {
        return medalCount;
    }

    /**
     * @param medalCount the medalCount to set
     */
    public void setMedalCount(int medalCount) {
        this.medalCount = medalCount;
    }

    public boolean matchDetails(String countryName, String type){
        return (country.equals(countryName) && eventType.equals(type));
    }

}

--GoldByCriteria

public class GoldByCriteria {

    private String country;
    private int goldMedals;

    public GoldByCriteria() {}

    public GoldByCriteria(String country, int goldMedals) {
        this.country = country;
        this.goldMedals = goldMedals;
    }

    /**
     * @return the country
     */
    public String getCountry() {
        return country;
    }
    /**
     * @param country the country to set
     */
    public void setCountry(String country) {
        this.country = country;
    }
    /**
     * @return the goldMedals
     */
    public int getGoldMedals() {
        return goldMedals;
    }
    /**
     * @param goldMedals the goldMedals to set
     */
    public void setGoldMedals(int goldMedals) {
        this.goldMedals = goldMedals;
    }

    /* (non-Javadoc)
     * @see java.lang.Object#hashCode()
     */
    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((country == null) ? 0 : country.hashCode());
        return result;
    }

    /* (non-Javadoc)
     * @see java.lang.Object#equals(java.lang.Object)
     */
    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        GoldByCriteria other = (GoldByCriteria) obj;
        if (country == null) {
            if (other.country != null)
                return false;
        } else if (!country.equals(other.country))
            return false;
        return true;
    }

    /* (non-Javadoc)
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        return country + " - " + goldMedals;
    }

}

--实用程序

import java.util.ArrayList;
import java.util.List;

public class Util {

    /**
     * base on the criteria to get the number of gold
     * 
     * */
    public static final GoldByCriteria getGoldByCriteria(List<GoldByCriteria> list, String criteria) {
        for (GoldByCriteria goldByCriteria : list) {
            if(goldByCriteria.getCountry().equals(criteria)) {
                return goldByCriteria;
            }
        }
        return null;
    }

    /**
     * group by Country
     * */
    public static final List<GoldByCriteria> getGoldMedalsByCountry(List<GoldMedals> goldMedals) {
        List<GoldByCriteria> result = new ArrayList<GoldByCriteria>();
        for (GoldMedals e : goldMedals) {
            GoldByCriteria goldByCountry = Util.getGoldByCriteria(result, e.getCountry());
            if( goldByCountry != null) {
                goldByCountry.setGoldMedals(goldByCountry.getGoldMedals() + 1);
            } else {
                GoldByCriteria oneGold = new GoldByCriteria();
                oneGold.setCountry(e.getCountry());
                oneGold.setGoldMedals(e.getMedalCount());
                result.add(oneGold);
            }
        }
        return result;
    }


    /**
     * group by type
     * */
    public static final List<GoldByCriteria> getGoldMedalsByType(List<GoldMedals> goldMedals) {
        List<GoldByCriteria> result = new ArrayList<GoldByCriteria>();
        for (GoldMedals e : goldMedals) {
            GoldByCriteria goldByCountry = Util.getGoldByCriteria(result, e.getEventType());
            if( goldByCountry != null) {
                goldByCountry.setGoldMedals(goldByCountry.getGoldMedals() + 1);
            } else {
                GoldByCriteria oneGold = new GoldByCriteria();
                oneGold.setCountry(e.getEventType());
                oneGold.setGoldMedals(e.getMedalCount());
                result.add(oneGold);
            }
        }
        return result;
    }

}

--主要

import java.util.ArrayList;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        List<GoldMedals> goldMedals = new ArrayList<GoldMedals>();

        GoldMedals one = new GoldMedals("ITA", "Fencing", "Women's Individual Foil");
        GoldMedals two = new GoldMedals("POL", "Rowing", "Men's Quadruple Sculls");
        GoldMedals three = new GoldMedals("CHN", "Diving", "Men's 3m Springboard");
        GoldMedals four = new GoldMedals("CHN", "Diving", "Men's Synchronised 3m Springboard");

        goldMedals.add(one);
        goldMedals.add(three);
        goldMedals.add(two);
        goldMedals.add(four);

        //by country 
        List<GoldByCriteria> byCountries = Util.getGoldMedalsByCountry(goldMedals);

        for (GoldByCriteria goldByCountry : byCountries) {
            System.out.println(goldByCountry);
        }

        System.out.println("------------");
        //by Type

        List<GoldByCriteria> byType = Util.getGoldMedalsByType(goldMedals);

        for (GoldByCriteria goldByType : byType) {
            System.out.println(goldByType);
        }
    }
}

您应该将 GoldByCriteria 中的属性“country”更改为更好的名称,例如“criteria”。为了一个快速的代码,我用国家测试了它。

希望对您有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-08-31
    • 1970-01-01
    • 2012-07-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多