1

所以我在创建这个函数时遇到了麻烦,它必须找到一个 char 数组的整数平均值。

这是我的数组 char[]letters = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J'} ;

我试图键入 cast 以找到整数平均值,如 A= 32 j= 74。添加整数值并将其转回一个字符,但此刻卡住了。

/********************************************************************************
 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) );
}
4

3 回答 3

2

这是不正确的:

 total = total + letters[letters.length];

此操作将超出数组末尾的值添加到total,触发异常。

你需要一个循环:

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

您还可以使用for-in循环,如下所示:

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

您也在铸造total而不是铸造除法的结果:

mean = (char)total / letters.length;

应该替换为

mean = (char)(total / letters.length); // Note the added parentheses
于 2012-10-28T23:10:16.323 回答
1

首先-您的方法是递归的,它会中断。我想您想将字符转换为十进制 ascii 代码。试试这个:

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
}
于 2012-10-28T23:17:21.173 回答
0

这是一个关于如何做到这一点的练习吗?如果没有,请使用字符数组并使用 .digit()。

如果是这样,那么你在正确的轨道上,但我的第一个想法是循环,减去适当的值以将 ascii 字符更改为数字,也许将它们粘贴在一个新数组中,然后再次循环以求平均值。

老实说,我看不出你是如何用 0 个循环来尝试这个的。

于 2012-10-28T23:15:38.533 回答