我想在java中製作一個程序,您可以添加人的生日,名字,birthmonths和birthyears。我希望能夠列出月份和每月出生人數的列表。我有以下代碼,2個類作爲「人」類和「分析器」類。這是下面的代碼,不能讓arraylist使用索引和while循環做一個列表
import java.util.*;
/*
* This project will keep track of which day
* (1 to 31) and which month (1 to 12)in which
* people are born.
* Look to LogAnalyzer for clue.
*/
public class Person
{
private int birthDay;
private int birthMonth;
private int birthYear;
private String name;
public Person(String name, int birthDay, int birthMonth, int birthYear)
{
this.name = name;
if(birthDay >= 1 && birthDay <= 31){
this.birthDay = birthDay;
}
else {
this.birthDay = -1;
}
if(birthMonth >= 1 && birthMonth <= 12){
this.birthMonth = birthMonth;
}
else {
this.birthMonth = -1;
}
this.birthYear = birthYear;
}
public String getName()
{
return name;
}
public int getBirthDay()
{
return birthDay;
}
public int getBirthMonth()
{
return birthMonth;
}
public int getBirthYear()
{
return birthYear;
}
public String toString()
{
return "Name: " + getName() + " BirthDay: " + getBirthDay() +
" BirthMonth: " + getBirthMonth() + " BirthYear: " +
getBirthYear();
}
}
import java.util.ArrayList;
import java.util.Iterator;
public class Analyzer
{
// instance variables - replace the example below with your own
private int []birthDayStats;
private int []birthMonthStats;
private ArrayList people;
/**
* Constructor for objects of class Analyzer
*/
public Analyzer()
{
people = new ArrayList();
}
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]++;
birthDayStats[birthDay]++;
}
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 (birthMonthStats[index]);
index++;
}
}
}
我在遇到麻煩的代碼是「printmonthlist」方法,我試圖將其打印出來,但它不打印。我希望它能打印出12個月的月份清單和每個月出生的人數。如果你們中的任何人都能幫我弄清楚謝謝。
順便說一句,你可以使用['LocalDate'](https://docs.oracle.com/javase/8/ docs/api/java/time/LocalDate.html)日期類而不僅僅是整數。 'LocalDate.of(y,m,d)'和['YearMonth'](https://docs.oracle.com/javase/8/docs/api/java/time/YearMonth.html)&['MonthDay' ](https://docs.oracle.com/javase/8/docs/api/java/time/MonthDay.html)類可能會有用。 –