6 Replies Latest reply: Dec 4, 2007 11:35 AM by 807603

# Newbie Array Question - Count number of elements

Hi all I'm new to Java and programming in general and was just wondering if anyone can tell me how to count the number of elements returned in the following code.
``````int year = 0;
int indexyear = 0;
year = input.nextInt();

if (year <=0)
{pline();System.out.println("The year must be greater than 0"); AnotherGo();}

else if ( year >= 1)
{pline();System.out.println("The following people were born by " + year);pline();

while (indexyear < Peolpe.byears.length)
{
if (Peolpe.byears[indexyear] <= year)
{System.out.println(Peolpe.names[indexyear]  +  People.byears[indexyear]);}
indexyear++;
}``````
As you can see my code references an external class that has two arrays names and people, if I enter a 1976 as the year it returns the 3 people that were born in 1976 or earlier, however I can't figure out how to print out the number of people returned as I keep getting the total number of elements in the array as the answer.

Any help greatly appricated.

Edited by: Irish-Student on Dec 3, 2007 1:49 PM Put in code tags
• ###### 1. Re: Newbie Array Question - Count number of elements
You mean People.byears.length ?
• ###### 2. Re: Newbie Array Question - Count number of elements
I assume you're trying to count how many people this is true for:
``if (Peolpe.byears[indexyear] <= year)``
right?

If so, then create another int to use as the counter. Each time you enter that if block, you've found another person to count, so increment the counter. After the loop is over, print out the value of the counter.
• ###### 3. Re: Newbie Array Question - Count number of elements
``pline();``
Please tell me you don't have a method to print a blank line.
• ###### 4. Re: Newbie Array Question - Count number of elements
Hi all,

Thanks for the replies.

Quacked pline(); is just a call to a procedure I set up cause I'm to lasy to type out the full code System.out.println(); for empty lines.

Hunter9000
Am I right in saying that I've to do this?
``````int count= 0;

if (Peolpe.byears[indexyear])
{count++; System.out.println(Peolpe.names[indexyear]  +  People.byears[indexyear]);}``````
Cheers all
• ###### 5. Re: Newbie Array Question - Count number of elements
Yeah, that's pretty much it, buy you still need to compare Peolpe.byears[indexyear] to year in the if condition.
• ###### 6. Re: Newbie Array Question - Count number of elements
hunter thanks for that it worked a treat and sorry about the typo.