Write a program that reads a list of 10 values from the user. Put the values in an array. The program should read the array and then calculate and display the average of the even input values and the average of the odd input values. This should be done using objects, methods, and a tester class.
我无法弄清楚为什么会收到错误:
bad operand types for binary operator.
我不知道该改变什么.我知道我的mod(%)出了问题.
到目前为止,这是我的平均班级课程:
public class Average
{
private int[] numbers = new int[10];
double aveEven, aveOdd,sumEven=0,sumOdd=0;
int oddCounter=0, evenCounter=0;
public Average(int[] n)
{
numbers = n;
if (numbers % 2 == 0)/something is wrong here/
{
evenCounter++;
sumEven+=n;
}
else
{
oddCounter++;
sumOdd+=n;
}
}
public void aveEven()
{
for (int i = 0; i < numbers.length; i++)
{
aveEven = sumEven/evenCounter;
System.out.println("The even average is: " + aveEven);
}
}
public void aveOdd()
{
for(int i = l; i < numbers.length; i++)
{
aveOdd = sumOdd/oddCounter;
System.out.println("The odd average is: " + aveOdd);
}
}
}
对于AverageTester类,我具有以下内容:
import java.util.Scanner;
public class AverageTester
{public static void main(String[] args)
{
int[] integer = new int[10];
Scanner input = new Scanner(System.in);
for(int i=0 ; i < 10 ; i++)
{
System.out.print("Please enter a number : ");
integer[i] = input.nextInt();
}
Average example = new Average(integer);
example.aveOdd();
}
}
另外,如果您发现其他可能出错的信息,请告诉我.
谢谢.
解决方法:
数字是一个数组,因此数字%2无效.您应该遍历数组,并在数组的元素上使用%运算符. =运算符也应应用于数组的一个元素(即numbers [i]),而不是整个数组.
numbers = n;
for (int i = 0; i < numbers.length; i++) {
if (numbers[i] % 2 == 0) {
evenCounter++;
sumEven+=numbers[i];
} else {
oddCounter++;
sumOdd+=numbers[i];
}
}
至于aveEven和aveOdd,由于您已经在构造函数中计算了总和(或者至少看起来像您打算这样做),因此在这些方法中不需要循环.
编辑:
我最初假设您打算计算数组中偶数位置的数字平均值和奇数位置的数字平均值.再次阅读问题后,我认为奇数/偶数是指数字本身,因此我相应地更改了代码.