【发布时间】:2013-11-06 17:27:39
【问题描述】:
此代码不起作用, 它说calculateArray中的lessthaAverage(int)不能应用于(),我是初学者所以我还是不明白这个编码,这是问的问题,写一个面向对象的程序,随机生成一个1000的数组1 到 1000 之间的整数。 计算超过 500 个数字的出现次数,并找出这些数字的平均值。 计算小于平均值的数字,最后按降序对数字进行排序。 显示所有输出。请帮帮我!!!,谢谢...
import java.util.*;
import java.io.*;
//import java.util.random;
public class CalculateArray
{
//declare attributes
private int arr[] = new int[1000];
int i;
//generates an array of 1000 integers between 1 to 1000
public void genArr()
{
Random ran = new Random();
for(i = 0; i < arr.length; i++)
{
arr[i] = ran.nextInt(1000) + 1;
}
}
//Calculate the occurences of number more than 500
public int occNumb()
{
int count;
for(i = 0; i < arr.length; i++)
{
if(arr[i] > 500)
{
count++;
}
}
return count;
}
//find the average of the numbers
public int average()
{
int sum, aver;
for(i = 0; i < arr.length; i++)
{
sum += arr[i];
}
aver = sum/1000;
return aver;
}
//Count the number which is less than the average
public int lessthanAverage(int aver)
{
int cnt;
cnt = 0;
for(i = 0; i < arr.length; i++)
{
if(arr[i] < aver)
{
cnt++;
}
}
return cnt;
}
//finally sort the numbers in descending order.
public void sort(int[] num)
{
System.out.println("Numbers in Descending Order:" );
for (int i=0; i <= num.length; i++)
for (int x=1; x <= num.length; x++)
if (num[x] > num[x+1])
{
int temp = num[x];
num[x] = num[x+1];
num[x+1] = temp;
}
}
//Display all your output
public void display()
{
int count, aver;
System.out.println(arr[i] + " ");
System.out.println("Found " + count + " values greater than 500");
System.out.println("The average of the numbers is " + aver);
System.out.println("Found " + count + " values that less than average number ");
}
public static void main(String[] args)
{
CalculateArray show = new CalculateArray();
show.genArr();
int c= show.occNumb();
show.average();
int d=show.lessthanAverage();
show.sort(arr);
show.display();
}
}
【问题讨论】:
-
你能发布确切的错误信息吗?
-
你到底有什么错误?
-
与您的问题无关,但您不应在每次调用
genArr()时实例化一个新的Random对象。将ran设为静态并实例化一次,例如在 main 中或在类声明级别静态地实例化。 -
该方法是使用参数 public int lessthanAverage(int aver) 定义的,但是当您在 main 方法中使用它时。你没有传递一个值。应该有编译器错误。此外,对于属性 arr (private int arr[] = new int[1000];),它是非静态的。您不能直接在 main 方法中使用它,这是一个静态方法。也会出现编译器错误。
-
是否有某些原因您正在编写自己的排序而不是使用
Arrays.sort?