2017-09-25 44 views
0

我有這個項目,我讓你導入你的生日,名字,birthyear和birthmonth。我試圖找到一個方法,找到最流行的生日,例如,「最流行的日期是空白生日的第16日。我知道我將不得不循環birthDaysStats,但我會怎麼寫? 這是我的代碼,而我遇到問題的方法是在底部。如何循環找到Arraylist的最大值

import java.util.ArrayList; 
import java.util.Collections; 

public class Analyzer { 
    // instance variables - replace the example below with your own 
    private final static int DAYS_PER_MONTH = 31; 
    private final static int MONTHS_PER_YEAR = 12; 
    private int[] birthDayStats; 
    private int[] birthMonthStats; 
    private ArrayList<Person> people; 

    /** 
    * Constructor for objects of class Analyzer 
    */ 
    public Analyzer() { 
     this.people = new ArrayList<Person>(); 
     this.birthDayStats = new int[Analyzer.DAYS_PER_MONTH]; 
     this.birthMonthStats = new int[Analyzer.MONTHS_PER_YEAR]; 
    } 

    public void addPerson(String name, int birthDay, int birthMonth, int birthYear) { 
     Person person = new Person(name, birthDay, birthMonth, birthYear); 
     if (person.getBirthDay() != -1 || person.getBirthMonth() != -1) { 
      people.add(person); 
      birthMonthStats[birthMonth - 1]++; 
      birthDayStats[birthDay - 1]++; 
     } else { 
      System.out.println("Your current Birthday is " + birthDay + " or " 
        + birthMonth + " which is not a correct number 1-31 or 1-12 please put in a correct number "); 
     } 
    } 

    public void printPeople() { //prints all people in form: 「 Name: Tom Month: 5 Day: 2 Year: 1965」 
     int index = 0; 
     while (index < people.size()) { 
      Person person = (Person) people.get(index); 
      System.out.println(person); 
      index++; 
     } 
    } 

    public void printMonthList() { //prints the number of people born in each month Sample output to the right with days being similar 
     int index = 0; 
     while (index < birthMonthStats.length) { 
      System.out.println("Month number " + (index + 1) + " has " + birthMonthStats[index] + " people"); 
      index++; 
     } 
    } 

    public void mostPopularDay() { //finds the most popular Day of the year 
     Object obj = Collections.mostPopularDay(birthDayStats); 
     System.out.println(obj); 
    } 
} 
+2

什麼是對象obj = Collections.mostPopularDay(birthDayStats);'應該這樣做?這看起來像各種無效。你已經嘗試過什麼來解決這個問題? – Carcigenicate

+1

'Collections.mostPopularDay'不是一件事...你期望做什麼? –

+0

[通過數組遍歷 - java](https://stackoverflow.com/questions/14489590/iterating-through-array-java) –

回答

1

你必須遍歷數組你持有的日子裏,找到最高計數和返回值的索引。

public int mostPopularDay() { //finds the most popular Day of the year 
    int popularDay = 0; 
    int max = -1; 
    for(int i = 0; i < birthDayStats.length; i++) { 
     if(birthDayStats[i] > max) { 
      max = birthDayStats[i]; 
      popularDay = i;    
     } 
    } 
    return popularDay + 1; //Adding +1 since there is no 0th day of the month 
} 

請記住,這隻會返回生日中最受歡迎的日子,而不是最受歡迎的日子。但我認爲這是你特德。

+0

我得到的錯誤不兼容的類型:根據 – Stevo4586

+0

返回popularDay; – Stevo4586

+0

我更新了它,應該立即工作。方法簽名規定了'void',它應該是返回類型的'int'。 –