I have to create a method in JAVA
where a user define a number, and the method search inside an array how many time this number exists, like this:
int[] age = {21, 23, 21, 29, 18};
If the user enters: 21
The output should be:
21 exist 2 times
I made this code:
public static int numAgeReader(int[] ageToSearch)
{
Scanner scan = new Scanner(System.in);
int n = 0;
int counter=0;
System.out.println("Please enter an age:");
n = scan.nextInt();
//Searching the ages Array to see how many persons have this age
for(int i=0; i<ageToSearch.length; i++)
{
if(n==ageToSearch[i])
counter += counter; //counter = counter + 1
}
return counter;
}
And of course I called it in the main function:
System.out.println(numAgeReader(ages));
Where ages is the array that I previously filled it.
The result is always: 0
EDIT
This method should return an average of an array:
public static double average(int[] ageArray)
{
//double aver=0.0;
int sum = 0;
//Calculating the sum of the age array
for (int i=0; i<ageArray.length; i++)
{
sum = sum + ageArray[i];
}
//Calculating the average:
return(sum/ageArray.length);
//return aver;
}
The result should be sometimes like 25.33 or 18.91, but the returned value is always like this: 25.0 or 19.0 or 89.0