javip
javip

Reputation: 259

Finding the integer average in a char array

So im having trouble creating this function that has to find the integer average of a char array.

This is my array char[]letters = {'A', 'B' , 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J'};

Im trying to type cast to find the integer average like A= 32 j= 74. adding the integer value and turning it back in a character but am stuck at the moment.

/********************************************************************************
 This function will calculate the integer average of characters in the array
********************************************************************************/
public static void average( char [] letters )
{
     int total = 0;

     char mean;


     total = total + letters[letters.length];
     mean = (char)total / letters.length;

     System.out.println("The value is " + average( letters) );
}

Upvotes: 1

Views: 1267

Answers (3)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726809

This is incorrect:

 total = total + letters[letters.length];

This operation adds the value past the end of the array to total, triggering an exception.

You need a loop here:

for (int i = 0 ; i != letters.length ; i++)
    total += letters[i];

You can also use the for-in loop, like this:

for (char ch : letters)
    total += ch;

You are also casting total instead of casting the result of the division:

mean = (char)total / letters.length;

should be replaced with

mean = (char)(total / letters.length); // Note the added parentheses

Upvotes: 2

reederz
reederz

Reputation: 971

First of all- your method is recursive and it will break. I suppose you want to cast chars into their decimal ascii codes. Try this:

public static int average( char [] letters )
{
     int total = 0;

     for(int i = 0; i < letters.length; i++){
       total += (int)letters[i];
     }

     return total / letters.length; //or cast it back to char if you prefer
}

Upvotes: 1

Jake Sellers
Jake Sellers

Reputation: 2439

Is this an exercise on how to do this for the sake of doing it? If not, use a Character array and use .digit().

If so, then you are on the right track, but my first thought is to just loop through, subtracting the appropriate value to change the ascii chars to numbers, maybe stick them in a new array, and loop again to average.

Honestly I don't see how you are even attempting this with 0 loops.

Upvotes: 0

Related Questions