This question already has answers here:
How to create method for age calculation method in android
(7 answers)
Closed 4 months ago.
I have DatePicker Dialog, When I select date at that time I want to calculate age it's working but when I select date of current year at that time it showing the -1 age instead of 0 then how can solve this? Please help me to solve it.
My code is below:
public int getAge(int year, int month, int day) {
GregorianCalendar cal = new GregorianCalendar();
int y, m, d, noofyears;
y = cal.get(Calendar.YEAR);// current year ,
m = cal.get(Calendar.MONTH);// current month
d = cal.get(Calendar.DAY_OF_MONTH);// current day
cal.set(year, month, day);// here ur date
noofyears = (int) (y - cal.get(Calendar.YEAR));
LOGD("Age......", String.valueOf(noofyears));
if ((m < cal.get(Calendar.MONTH)) || ((m == cal.get(Calendar.MONTH)) && (d < cal.get(Calendar.DAY_OF_MONTH)))) {
--noofyears;
}
LOGD("Age......", String.valueOf(noofyears));
if (noofyears != 0) {
ageCount = noofyears;
} else {
ageCount = 0;
}
if (noofyears < 0)
throw new IllegalArgumentException("age < 0");
return noofyears;
}
java.time
For the sake of completeness and being up-to-date concerning packages, here is the way using java.time (Java 8+).
Java
public int getAge(int year, int month, int dayOfMonth) {
return Period.between(
LocalDate.of(year, month, dayOfMonth),
LocalDate.now()
).getYears();
}
Kotlin
fun getAge(year: Int, month: Int, dayOfMonth: Int): Int {
return Period.between(
LocalDate.of(year, month, dayOfMonth),
LocalDate.now()
).years
}
Both snippets need the following imports from java.time:
import java.time.LocalDate;
import java.time.Period
It's not recommended to use java.util.Date and java.util.Calendar anymore except from situations where you have to involve considerably large amounts of legacy code.
See also Oracle Tutorial.
For projects supporting Java 6 or 7, this functionality is available via the ThreeTenBP,
while there is special version, the ThreeTenABP for API levels below 26 in Android.
UPDATE
There's API Desugaring now in Android, which makes (a subset of) java.time directly available (no backport library needed anymore) to API levels below 26 (not really down to version 1, but will do for most of the API levels that should be supported nowadays).
private int getAge(String dobString){
Date date = null;
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
try {
date = sdf.parse(dobString);
} catch (ParseException e) {
e.printStackTrace();
}
if(date == null) return 0;
Calendar dob = Calendar.getInstance();
Calendar today = Calendar.getInstance();
dob.setTime(date);
int year = dob.get(Calendar.YEAR);
int month = dob.get(Calendar.MONTH);
int day = dob.get(Calendar.DAY_OF_MONTH);
dob.set(year, month+1, day);
int age = today.get(Calendar.YEAR) - dob.get(Calendar.YEAR);
if (today.get(Calendar.DAY_OF_YEAR) < dob.get(Calendar.DAY_OF_YEAR)){
age--;
}
return age;
}
Here is a Kotlin extension of the Date class returning the age corresponding to a Date object
val Date.age: Int
get() {
val calendar = Calendar.getInstance()
calendar.time = Date(time - Date().time)
return 1970 - (calendar.get(Calendar.YEAR) + 1)
}
It is compatible for all Android versions. If you wonder what '1970' is, that's the Unix Epoch. The timestamp is 0 on January 1, 1970.
private boolean getAge(int year, int month, int day) {
try {
Calendar dob = Calendar.getInstance();
Calendar today = Calendar.getInstance();
dob.set(year, month, day);
int monthToday = today.get(Calendar.MONTH) + 1;
int monthDOB = dob.get(Calendar.MONTH)+1;
int age = today.get(Calendar.YEAR) - dob.get(Calendar.YEAR);
if (age > 18) {
return true;
} else if (age == 18) {
if (monthDOB > monthToday) {
return true;
} else if (monthDOB == monthToday) {
int todayDate = today.get(Calendar.DAY_OF_MONTH);
int dobDate = dob.get(Calendar.DAY_OF_MONTH);
if (dobDate <= todayDate) { // should be less then
return true;
} else {
return false;
}
} else {
return false;
}
} else {
return false;
}
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
public static int getPerfectAgeInYears(int year, int month, int date) {
Calendar dobCalendar = Calendar.getInstance();
dobCalendar.set(Calendar.YEAR, year);
dobCalendar.set(Calendar.MONTH, month);
dobCalendar.set(Calendar.DATE, date);
int ageInteger = 0;
Calendar today = Calendar.getInstance();
ageInteger = today.get(Calendar.YEAR) - dobCalendar.get(Calendar.YEAR);
if (today.get(Calendar.MONTH) == dobCalendar.get(Calendar.MONTH)) {
if (today.get(Calendar.DAY_OF_MONTH) < dobCalendar.get(Calendar.DAY_OF_MONTH)) {
ageInteger = ageInteger - 1;
}
} else if (today.get(Calendar.MONTH) < dobCalendar.get(Calendar.MONTH)) {
ageInteger = ageInteger - 1;
}
return ageInteger;
}
Consider Today's Date - 30th August 2020
If Birthdate - 29th July 1993, the output - 27
If Birthdate - 29th August 1993, the output - 27
If Birthdate - 30th August 1993, the output - 27
If Birthdate - 31st August 1993, the output - 26
If Birthdate - 31st September 1993, the output - 26
Now for kotlin Language:
import java.util.Calendar
fun main(args: Array<String>) {
print(getAge(yyyy,mm,dd))
}
fun getAge(year: Int, month: Int, day: Int): String {
val dob = Calendar.getInstance()
val today = Calendar.getInstance()
dob.set(year, month, day)
var age = today.get(Calendar.YEAR) - dob.get(Calendar.YEAR)
if (today.get(Calendar.DAY_OF_YEAR) < dob.get(Calendar.DAY_OF_YEAR)) {
age--
}
val ageInt = age + 1
return ageInt.toString()
}
private void calculateAge() {
age.calcualteYear();
age.calcualteMonth();
age.calcualteDay();
age.calculateMonths();
age.calTotalWeeks();
age.calTotalHours();
age.calTotalMins();
age.calTotalSecs();
age.calTotalMilsecs();
// Toast.makeText(getContext(), "click the resulted button"+age.getResult() , Toast.LENGTH_SHORT).show();
result.setText("AGE (DD/MM/YY) :" + age.getResult());
}
after that create one class
public class AgeCalculation {
private int startYear;
private int startMonth;
private int startDay;
private int endYear;
private int endMonth;
private int endDay;
private int resYear;
private int resMonth;
private int resDay;
private Calendar start;
private Calendar end;
public String getCurrentDate()
{
end=Calendar.getInstance();
endYear=end.get(Calendar.YEAR);
endMonth=end.get(Calendar.MONTH);
endMonth++;
endDay=end.get(Calendar.DAY_OF_MONTH);
return endDay+":"+endMonth+":"+endYear;
}
public void setDateOfBirth(int sYear, int sMonth, int sDay)
{
startYear=sYear;
startMonth=sMonth;
startDay=sDay;
}
public void calcualteYear()
{
resYear=endYear-startYear/(365);
}
public void calcualteMonth()
{
if(endMonth>=startMonth)
{
resMonth= endMonth-startMonth;
}
else
{
resMonth=endMonth-startMonth;
resMonth=12+resMonth;
resYear--;
}
}
public void calcualteDay()
{
if(endDay>=startDay)
{
resDay= endDay-startDay;
}
else
{
resDay=endDay-startDay;
resDay=30+resDay;
if(resMonth==0)
{
resMonth=11;
resYear--;
}
else
{
resMonth--;
}
}
}
public String getResult()
{
return resDay+":"+resMonth+":"+resYear;
}
public String getAge(int year, int month, int day) {
Calendar dob = Calendar.getInstance();
Calendar today = Calendar.getInstance();
dob.set(year, month-1, day);
int age = today.get(Calendar.YEAR) - dob.get(Calendar.YEAR);
if (today.get(Calendar.DAY_OF_YEAR) < dob.get(Calendar.DAY_OF_YEAR)) {
age--;
}
Integer ageInt = new Integer(age);
String ageS = ageInt.toString();
return ageS;
}
static int calculateAge(int birthdayDay, int birthdayMonth, int birthdayYear)
{
DateTime date = DateTime(birthdayYear, birthdayMonth, birthdayDay).toLocal();
DateTime now = DateTime.now().toLocal();
return now.difference(date).inDays ~/ 365.2425;
}
public int getAge(int year, int month, int day) {
final Calendar birthDay = Calendar.getInstance();
birthDay.set(year, month, day);
final Calendar current = Calendar.getInstance();
if (current.getTimeInMillis() < birthDay.getTimeInMillis())
throw new IllegalArgumentException("age < 0");
int age = current.get(Calendar.YEAR) - birthDay.get(Calendar.YEAR);
if (birthDay.get(Calendar.MONTH) > current.get(Calendar.MONTH) ||
(birthDay.get(Calendar.MONTH) == current.get(Calendar.MONTH) &&
birthDay.get(Calendar.DATE) > current.get(Calendar.DATE)))
age--;
return age;
}
This is how I implement in my source code, I tested. Hope that it is useful :
public static int getAge(String dateTime, String currentFormat) {
SimpleDateFormat dateFormat = new SimpleDateFormat(currentFormat);
try {
Date date = dateFormat.parse(dateTime);
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH);
int day = calendar.get(Calendar.DAY_OF_MONTH);
Date currentDate = new Date();
Calendar currentCalendar = Calendar.getInstance();
currentCalendar.setTime(currentDate);
int currentYear = currentCalendar.get(Calendar.YEAR);
int currentMonth = currentCalendar.get(Calendar.MONTH);
int currentDay = currentCalendar.get(Calendar.DAY_OF_MONTH);
int deltaYear = currentYear - year;
int deltaMonth = currentMonth - month;
int deltaDay = currentDay - day;
if (deltaYear > 0) {
if (deltaMonth < 0) {
deltaYear --;
} else if (deltaDay < 0){
deltaYear --;
}
return deltaYear;
}
} catch (java.text.ParseException e) {
e.printStackTrace();
}
return 0;
}
String getAgeInOther(int year, int month, int day) {
Calendar today = Calendar.getInstance();
Calendar birth = Calendar.getInstance();
birth.set(year, month, day);
Calendar temp = Calendar.getInstance();
temp.set(year, month, day);
int totalDays = 0;
int intMonth=0,intDays=0;
for (int iYear = birth.get(Calendar.YEAR); iYear <= today.get(Calendar.YEAR); iYear++) {
if (iYear == today.get(Calendar.YEAR) && iYear == birth.get(Calendar.YEAR)) {
for (int iMonth = birth.get(Calendar.MONTH); iMonth <= today.get(Calendar.MONTH); iMonth++) {
temp.set(iYear, iMonth, 1);
if ((iMonth == today.get(Calendar.MONTH)) && (iMonth == birth.get(Calendar.MONTH))) {
totalDays += today.get(Calendar.DAY_OF_MONTH) - birth.get(Calendar.DAY_OF_MONTH);
} else if ((iMonth != today.get(Calendar.MONTH)) && (iMonth != birth.get(Calendar.MONTH))) {
totalDays += temp.getActualMaximum(Calendar.DAY_OF_MONTH);
intMonth++;
}else if ((iMonth == birth.get(Calendar.MONTH))) {
totalDays +=( birth.getActualMaximum(Calendar.DAY_OF_MONTH)- birth.get(Calendar.DAY_OF_MONTH));
} else if ((iMonth == today.get(Calendar.MONTH))){
totalDays += today.get(Calendar.DAY_OF_MONTH);
if (birth.get(Calendar.DAY_OF_MONTH)<today.get(Calendar.DAY_OF_MONTH))
{
intMonth++;
intDays=today.get(Calendar.DAY_OF_MONTH)-birth.get(Calendar.DAY_OF_MONTH);
}else {
temp.set(today.get(Calendar.YEAR),today.get(Calendar.MONTH)-1,1);
intDays=temp.getActualMaximum(Calendar.DAY_OF_MONTH)-birth.get(Calendar.DAY_OF_MONTH)+today.get(Calendar.DAY_OF_MONTH);
}
}
}
} else if ((iYear != today.get(Calendar.YEAR)) && (iYear != birth.get(Calendar.YEAR))) {
for (int iMonth = 0; iMonth < 12; iMonth++) {
temp.set(iYear, iMonth, 1);
totalDays += temp.getActualMaximum(Calendar.DAY_OF_MONTH);
intMonth++;
}
} else if (((iYear) == birth.get(Calendar.YEAR))) {
for (int iMonth = birth.get(Calendar.MONTH); iMonth < 12; iMonth++) {
temp.set(iYear, iMonth, 1);
if ((iMonth == birth.get(Calendar.MONTH))) {
totalDays += (birth.getActualMaximum(Calendar.DAY_OF_MONTH)-birth.get(Calendar.DAY_OF_MONTH));
} else {
intMonth++;
totalDays += temp.getActualMaximum(Calendar.DAY_OF_MONTH);
}
}
} else if (iYear == today.get(Calendar.YEAR)) {
for (int iMonth = 0; iMonth <= today.get(Calendar.MONTH); iMonth++) {
temp.set(iYear, iMonth, 1);
if ((iMonth == today.get(Calendar.MONTH))) {
totalDays += today.get(Calendar.DAY_OF_MONTH);
if (birth.get(Calendar.DAY_OF_MONTH)<today.get(Calendar.DAY_OF_MONTH))
{
intMonth++;
intDays=today.get(Calendar.DAY_OF_MONTH)-birth.get(Calendar.DAY_OF_MONTH);
}else {
temp.set(today.get(Calendar.YEAR),today.get(Calendar.MONTH)-1,1);
intDays=temp.getActualMaximum(Calendar.DAY_OF_MONTH)-birth.get(Calendar.DAY_OF_MONTH)+today.get(Calendar.DAY_OF_MONTH);
}
} else {
intMonth++;
totalDays += temp.getActualMaximum(Calendar.DAY_OF_MONTH);
}
}
}
}
int ageYear=intMonth/12;
int ageMonth=intMonth%12;
int ageDays=intDays;
//TODO if you want age in YEAR:MONTH:DAY REMOVE COMMENTS
//TODO return ageYear+":"+ageMonth+":"+ageDays;
return ""+totalDays;//todo TOTAL AGE IN DAYS
}
public static String calculateAge(String strDate) {
int years = 0;
int months = 0;
int days = 0;
try {
long timeInMillis = Long.parseLong(strDate);
Date birthDate = new Date(timeInMillis);
//create calendar object for birth day
Calendar birthDay = Calendar.getInstance();
birthDay.setTimeInMillis(birthDate.getTime());
//create calendar object for current day
long currentTime = System.currentTimeMillis();
Calendar now = Calendar.getInstance();
now.setTimeInMillis(currentTime);
//Get difference between years
years = now.get(Calendar.YEAR) - birthDay.get(Calendar.YEAR);
int currMonth = now.get(Calendar.MONTH) + 1;
int birthMonth = birthDay.get(Calendar.MONTH) + 1;
//Get difference between months
months = currMonth - birthMonth;
//if month difference is in negative then reduce years by one and calculate the number of months.
if (months < 0) {
years--;
months = 12 - birthMonth + currMonth;
if (now.get(Calendar.DATE) < birthDay.get(Calendar.DATE))
months--;
} else if (months == 0 && now.get(Calendar.DATE) < birthDay.get(Calendar.DATE)) {
years--;
months = 11;
}
//Calculate the days
if (now.get(Calendar.DATE) > birthDay.get(Calendar.DATE))
days = now.get(Calendar.DATE) - birthDay.get(Calendar.DATE);
else if (now.get(Calendar.DATE) < birthDay.get(Calendar.DATE)) {
int today = now.get(Calendar.DAY_OF_MONTH);
now.add(Calendar.MONTH, -1);
days = now.getActualMaximum(Calendar.DAY_OF_MONTH) - birthDay.get(Calendar.DAY_OF_MONTH) + today;
} else {
days = 0;
if (months == 12) {
years++;
months = 0;
}
}
//adarsh
if (currMonth > birthMonth) {
if (birthDay.get(Calendar.DATE) > now.get(Calendar.DATE)) {
months = months - 1;
}
}//---------------------------------
} catch (Exception e) {
e.printStackTrace();
}
//Create new Age object
return years + " Y " + months + " M " + days + " days";
}
Here is my solution in Kotlin:
import java.time.LocalDateTime
fun getAge(birthYear: Int, birthMonth: Int, birthDay: Int): Int {
var age: Int = LocalDateTime.now().year - birthYear
if (birthMonth > LocalDateTime.now().monthValue || birthMonth == LocalDateTime.now().monthValue && birthDay > LocalDateTime.now().dayOfMonth) { age-- }
if (age < 0) { age = 0 }
return age
}
int age =0;
age = yearLatest - yearBirth;
if (monthAge > currentMonth) {
if (age != 0) {
age = age - 1;
}
} else if(monthAge == currentMonth){
if (dayAge > currentDay) {
if (age != 0) {
age = age - 1;
}
}
}
return age;
If we want to directly check if age is below or above X age then we can use LocalDate type, work for all the Android API levels.
LocalDate.now().minusYears(18).isBefore(value) //value is your localDate
This is the shortest I could get it to.
static int calculateAge(Calendar birthDay){
Calendar today = Calendar.getInstance();
int age = today.get(Calendar.YEAR) - birthDay.get(Calendar.YEAR);
if (birthDay.get(Calendar.DAY_OF_YEAR) < today.get(Calendar.DAY_OF_YEAR)) {
age--;
}
return age;
}
New Language Dart using DateTime
static int getPerfectAgeInYears(DateTime dob,DateTime today) {
dob = DateTime(dob.year,dob.month,dob.day);
int ageInteger = 0;
today = DateTime(today.year,today.month,today.day);
ageInteger = today.year-dob.year;
if (today.month == dob.month) {
if (today.day < dob.day) {
ageInteger = ageInteger - 1;
}
} else if (today.month < dob.month) {
ageInteger = ageInteger - 1;
}
return ageInteger;}
Call as print(getPerfectAgeInYears(DateTime(2000,6,4),DateTime.now()));
Consider Today's Date - 30th August 2020
If Birthdate - 29th July 1993, the output - 27
If Birthdate - 29th August 1993, the output - 27
If Birthdate - 30th August 1993, the output - 27
If Birthdate - 31st August 1993, the output - 26
If Birthdate - 31st September 1993, the output - 26
Related
So currently studying OOP, I have encountered a problem regarding why the numbers are not getting filtered by my range in the if and else statements, and also one more thing on the last part of the code there should be something with the lines of "public String showDetails()" but I don't know what is inside of it.
package com.xble.department.domain
public class Person
{
private String name;
private int EmpNo;
private int age;
public Person()
{
}
public Person(String n, int en, int a)
{
name = n;
if((en < 0) && (en >= 1) && (en <= 999999))
en = 0;
else
EmpNo = en;
if((a < 0) && (a >= 1) && (a <= 65))
a = 0;
else
age = a;
}
public void setName(String n)
{
name=n;
}
public void setEmpNo(int en)
{
if((en < 0) && (en >= 1) && (en <= 999999))
en = 0;
else
EmpNo = en;
}
public void setAge(int a)
{
if((a < 0) && (a >= 1) && (a <= 65))
a = 0;
else
age = a;
}
public String getName()
{
return name;
}
public int getEmpNo()
{
return EmpNo;
}
public int getAge()
{
return age;
}
//public String showDetails()
}
Here's your problem:
(en < 0) && (en >= 1)
This can never be true. For any given int value of en, it can not be below 0 and above or equal 1. This same condition is repeated in all the if statements.
Regarding the showDtails() method it looks like there should be some logic that returns a string, presumably with the details of this Person.
I am new to selenium automation, I have written a script to pick check in and check out dates from webpage of tripadvisor.in. I hope the code and xpaths are correct coz out of 7 or 8 executions the scrips successfully running only once. I thought abt synchronization issue and tried adding all types of waits but still the execution getting stuck as calendar. Sometimes stucking at check-in date, sometimes at check-out date but sometimes working fine. Can I get help to sort this issue plz...
public void selectCheckDate(String date, WebElement forwardArrow) {
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
try {
Date expectedDate = dateFormat.parse(prop.getProperty(date));
String day = new SimpleDateFormat("dd").format(expectedDate);
String month = new SimpleDateFormat("MMMM").format(expectedDate);
String year = new SimpleDateFormat("yyyy").format(expectedDate);
String expectedMonthYear = month + " " + year;
logger.log(Status.INFO, "Expected Month and year: "+expectedMonthYear);
WebDriverWait wait = new WebDriverWait(driver, 20);
String dd1 = "", dd2 = "";
String d1 = null, d2 = null;
boolean flag1 = false;
boolean flag2 = false;
while (true) {
String displayDate1 = driver.findElement(By.xpath("//*[#class='vr-datepicker-LargeStyles__caption--Srrff']/div")).getText();
String displayDate2 = driver.findElement(By.xpath("(//*[#class='vr-datepicker-LargeStyles__caption--Srrff']/div)[2]")).getText();
if (displayDate1.contains(expectedMonthYear)) {
//addWait();
for (int i = 1; i <= 5; i++) {
for (int j = 1; j <= 7; j++) {
d1 = "//*[#id='BODY_BLOCK_JQUERY_REFLOW']/div[14]/div/div/div[2]/div/div/div[2]/div[1]/div[3]/div["
+ i + "]/div[" + j + "]";
boolean ex = isElementExists(d1);
if(ex==true) {
dd1 = driver.findElement(By.xpath(d1)).getText();
if (dd1.equals(day)) {
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath(d1))).click();
//driver.findElement(By.xpath(d1)).click();
flag1 = true;
break;
}
}
}
if (flag1 == true) {
break;
}
}
if (flag1 == true) {
reportPass("Entered date: "+prop.getProperty(date));
break;
}
} else if (displayDate2.contains(expectedMonthYear)) {
//addWait();
for (int i = 1; i <= 5; i++) {
for (int j = 1; j <= 7; j++) {
d2 = "//*[#id='BODY_BLOCK_JQUERY_REFLOW']/div[14]/div/div/div[2]/div/div/div[2]/div[2]/div[3]/div["
+ i + "]/div[" + j + "]";
boolean ex1 = isElementExists(d2);
if(ex1==true) {
dd2 = driver.findElement(By.xpath(d2)).getText();
if (dd2.equals(day)) {
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath(d2))).click();
//driver.findElement(By.xpath(d2)).click();
flag2 = true;
break;
}
}
}
if (flag2 == true) {
break;
}
}
if (flag2 == true) {
reportPass("Entered date: "+prop.getProperty(date));
break;
}
} else {
forwardArrow.click();
}
}
} catch (ParseException e) {
reportFail(e.getMessage());
}
}
I'm trying to make a program in java that you can add people's birthdays, names, birthmonths, and birthyears. I want to be able to print out a list with month and number of people born in each month. I have the following code with 2 classes one as a "person" class and "analyzer" class. Here is the following code,
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++;
}
}
}
the code i'm having trouble is the "printmonthlist" method i'm trying to print it but it doesn't print. I want it to print out the month list of 12 months and the number of people born in each month. If any of you could help me figure it out thanks.
You forgot to initialize your arrays. As you can see in my code down here I initialized the arrays with two constants in the Analyzer creation.
NB: for readability I just changed a little bit your log in the printMonthList() method
import java.util.ArrayList;
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>();
// A default value of 0 for arrays of integral types is guaranteed by the language spec
this.birthDayStats = new int[Analyzer.DAYS_PER_MONTH];
// A default value of 0 for arrays of integral types is guaranteed by the language spec
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++;
}
}
}
I've tried to create some list with increase number after some calculation each month for a year.
For example, in month 1 number = 1, month 2 number = 3, month 3 number = 5.
The calculation is like this number[i] = i + number[i - 1]. Which i is the month.
I want to show all the list like this
Month[1] = 1,
Month[2] = 3,
Month[3] = 5,
Month[4] = 7,
Month[5] = 9,
Month[6] = 11,
Month[7] = 13,
...
Month[12] = 23
Here's my Controller
for (i = 1; i <= 12; i++)
{
List<int> number = new List<int>();
if (i <= 12)
{
number[i] = a(i, number[i - 1]);
}
else
{
//something else
}
}
Here's my a function
public int a(int month, int number)
{
try
{
a = month + number;
}
catch (Exception ex)
{
throw ex;
}
return a;
}
But, when executed i'm getting this error
Index was out of range. Must be non-negative and less than the size of the collection.
I've change the controller into this
for (i = 0; i <= 12; i++)
{
//...
}
But have the same error. Can someone help me? Why I'm getting this error?
Try this
Fiddle demo
int[] number = new int[13];
for (int i = 1; i <= 12; i++)
{
if (i <= 12)
{
number[i] = a(i, number[i - 1]);
}
else
{
//something else
}
}
int j = 1;
List<int> item = new List<int>();
foreach (var a in number)
{
if (j <= 12)
{
item.Add(a);
}
else
{
break;
}
j++;
}
public int a(int month, int number)
{
int a = 0;
try
{
a = month + number;
}
catch (Exception ex)
{
throw ex;
}
return a;
}
I am working on DatePicker in android 1.5. I am trying to set Maximum and minimum date.Minimum date should be the current date and maximum date should be the date which I will supply from string as maxYear, maxMonth, maxDay.(Suppose Todays date=30/12/2011, but it selects 29/12/2011)
Everything working fine with minimum date.As it shows current date only.But on selection using minus button on picker, it selects a date less than today's date.
While in case of maximum date selection it selects day, month and year more than the maximum date.
How to restrict user not to select less than minimum date and maximum date. What extra condition I have to put to make it perfect?
enter code here
///Whole code same
mport java.sql.Date;
import java.util.Calendar;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.TimePicker;
import android.widget.Toast;
import android.widget.DatePicker.OnDateChangedListener;
public class DatePickerActivity extends Activity implements Button.OnClickListener {
public String dateOutput=null;
final Calendar c = Calendar.getInstance();
int minYear1 = c.get(Calendar.YEAR);
int minMonth1 = c.get(Calendar.MONTH);
int minDay1 = c.get(Calendar.DAY_OF_MONTH);
int maxYear = 2011;//
int maxMonth = 12;
int maxDay = 29;
int minYear = minYear1;
int minMonth = minMonth1;
int minDay = minDay1;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
DatePicker DateDP = (DatePicker) findViewById (R.id.ad_date_picker);
DateDP.init(minYear1, minMonth1, minDay1, new OnDateChangedListener()
{
public void onDateChanged(DatePicker view, int year, int monthOfYear, int dayOfMonth)
{
if (year < minYear)
view.updateDate(minYear, minMonth, minDay);
if (monthOfYear < minMonth && year == minYear )
view.updateDate(minYear, minMonth, minDay );
if (dayOfMonth < minDay && year == minYear && monthOfYear == minMonth)
view.updateDate(minYear, minMonth, minDay);
if (year > maxYear)
view.updateDate(maxYear, maxMonth, maxDay);
if (monthOfYear > maxMonth && year == maxYear)
view.updateDate(maxYear, maxMonth, maxDay);
if (dayOfMonth > maxDay && year == maxYear && monthOfYear == maxMonth)
view.updateDate(maxYear, maxMonth, maxDay);
dateOutput = String.format("Date Selected: %02d/%02d/%04d",
dayOfMonth, monthOfYear+1, year);
// Log.d("Debug", dateOutput);
Toast.makeText(DatePickerActivity.this,dateOutput, Toast.LENGTH_SHORT).show();
}}); // DateDP.init()
}
}
This way, i solved my problem
DateDP.init(minYear, minMonth, minDay, new OnDateChangedListener()
{
public void onDateChanged(DatePicker view, int year, int monthOfYear, int dayOfMonth)
{
if (year > maxYear ||monthOfYear > maxMonth && year == maxYear||
dayOfMonth > maxDay && year == maxYear && monthOfYear == maxMonth){
// Toast.makeText(DatePickerActivity.this,"max year", Toast.LENGTH_SHORT).show();
view.updateDate(maxYear, maxMonth, maxDay);
dateOutput = String.format("%04d-%02d-%02d",
maxYear, maxMonth+1, maxDay);
//Toast.makeText(DatePickerActivity.this,"maxYear "+dateOutput, Toast.LENGTH_SHORT).show();
}else if(year < minYear ||monthOfYear < minMonth && year == minYear||
dayOfMonth < minDay && year == minYear && monthOfYear == minMonth){
//Toast.makeText(DatePickerActivity.this,"min year", Toast.LENGTH_SHORT).show();
view.updateDate(minYear, minMonth, minDay );
dateOutput = String.format("%04d-%02d-%02d",
minYear, minMonth+1, minDay);
//Toast.makeText(ManageShowing.this,dateOutput, Toast.LENGTH_SHORT).show();
}else{
//Toast.makeText(ManageShowing.this,"else", Toast.LENGTH_SHORT).show();
dateOutput = String.format("%04d-%02d-%02d",
year, monthOfYear+1, dayOfMonth);
// Toast.makeText(ManageShowing.this,dateOutput, Toast.LENGTH_SHORT).show();
}
mDateDisplay.setText(dateOutput);
}}); // DateDP.init()