【发布时间】:2018-07-01 15:48:24
【问题描述】:
我正在编写一个应该用随机整数填充数组的类。数组的大小是通过扫描器类通过用户输入给出的。然后,您应该包括用于获取平均值、最小值和最大值的方法,以及用于显示随机整数的 toString 方法。我已经写出了类,但无法让方法在我的驱动程序中工作。我使用 array.getMax() 它返回一个不能应用于给定类型的 throw。而我的 String 只返回数组地址。谁能告诉我哪里出错了?
类:
import java.util.*;
public class RandomArray {
public int size;
private static Random gen = new Random();
public RandomArray()
{
Scanner scan = new Scanner(System.in);
System.out.print("Enter the size of the array: ");
size = scan.nextInt();
int[] array = new int[size];
for (int i = 0; i < array.length; i++)
array[i] = gen.nextInt(50) + 1;
}
public int getMax(int[] array)
{
int max = 0;
for (int i = 0; i < array.length; i++)
if (array[i] > max) {
max = array[i];
}
return max;
}
public int getMin(int[] array)
{
int min = 52;
for (int i = 0; i < array.length; i++)
if (array[i] < min) {
min = array[i];
}
return min;
}
public double getAvg(int[] array)
{
double total = (double) size;
double avg, sumOf;
int sum = 0;
for (int i : array)
sum += i;
sumOf = (double) sum;
avg = sumOf / total;
return avg;
}
public String toString(int[] array)
{
String result = "";
for (int i = 0; i < array.length; i++)
result = result + array[i];
return result;
}
}
这里是驱动程序(调用后我也不知道怎么做平均显示):
import java.util.*;
public class RandomArrayDriver {
public static void main(String[] args)
{
int value;
RandomArray one = new RandomArray();
one.getAvg();
one.getMax();
one.getMin();
System.out.print("The contents are: " + one.toString());
}
}
【问题讨论】:
-
请take the tour 了解该网站的运作方式以及此处的主题有哪些问题,并edit 相应地提出您的问题。另见:How to Debug Small Programs
-
在您的代码中,我没有看到您使用 Scanner 类的公共函数中的书面值
-
我建议包括抛出的异常的输出和堆栈跟踪。这将帮助人们更快地确定问题的根源。