1

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

4 Answers4

4

Change

counter += counter;

to

counter++;

Since counter is set to 0 at the beginning, counter += counter; has no effect on the counter variable, hence you'll always get 0 as the return value.

Mohammed Aouf Zouag
  • 17,042
  • 4
  • 41
  • 67
  • sir, I have a function that return the average I want this average to be like 25.33 and not like 25.00, the variable is double how to fix that ? –  Jan 29 '16 at 14:54
  • @androidnation update your post with the code of the function that you are talking about. Even though, I highly advise you to do more research about it. – Mohammed Aouf Zouag Jan 29 '16 at 14:55
  • @androidnation change `return(sum/ageArray.length);` to `return((double)sum/ageArray.length);`. Check this link for more about this issue: http://stackoverflow.com/questions/7286681/why-does-my-java-division-code-give-the-wrong-answer – Mohammed Aouf Zouag Jan 29 '16 at 14:59
  • @androidnation you're doing something wrong. Try to do more research, if you couldn't figure it on your own, post a new question with your problem in details. Good luck ! – Mohammed Aouf Zouag Jan 29 '16 at 15:06
3

You made a mistake here:

counter += counter;

You probably meant:

counter++;
Gaël J
  • 11,274
  • 4
  • 17
  • 32
2

When you are writing counter += counter you are actually adding 0 to itself every time.

You need to write counter++ or counter += 1

Adil Shaikh
  • 44,509
  • 17
  • 89
  • 111
1

Try to use this:

   counter++;

Instead of counter += counter;

Abdelhak
  • 8,299
  • 4
  • 22
  • 36