我正在尝试创建一个类,它接受一个数组作为参数,并返回该数组中的最小值、最大值、平均值和最频繁的元素。然而,当创建一个类的实例时,我得到了一个奇怪的错误,说Exception in thread "main" java.lang.NullPointerException at app.trackint.getmean(trackint.java:79)
,有人能帮我吗?感谢大家的帮助!感谢大家的帮助!
/**
*
* @author User
*/
import java.util.Arrays;
public class trackint{
private int[] array;
public trackint(int[] a){
a = new int[2];
}
public void getmax(int[] array){
// Initialize maximum element
int max = array[0];
for (int i = 1; i < array.length; i++) {
if (array[i] > max) {
max = array[i];
}
System.out.println(max);
}
}
public void getmin(int min){
min = array[0];
for (int i = 1; i < array.length; i++) {
if (array[i] < min) {
min = array[i];
}
System.out.println(min);
}
}
public void getmax(int max){
// Initialize maximum element
max = array[0];
for (int i = 1; i < array.length; i++) {
if (array[i] > max) {
max = array[i];
}
System.out.println(max);
}
}
public void getmean(){
// Initialize maximum element
float sum = 0;
for (int i = 0; i < array.length; i++) {
sum += array[i];
}
System.out.println( sum / array.length);
}
public void mostFrequent(int n, int[] array) {
// find the max frequency using linear
// traversal
int max_count = 1, res = array[0];
int curr_count = 1;
for (int i = 1; i < n; i++)
{
if (array[i] == array[i - 1])
curr_count++;
else
{
if (curr_count > max_count)
{
max_count = curr_count;
res = array[i - 1];
}
curr_count = 1;
}
}
// If last element is most frequent
if (curr_count > max_count)
{
max_count = curr_count;
res = array[n - 1];
}
System.out.println( res);
}
public static void main(String []args){
int[] array = {1,2,3,4,5};
trackint a = new trackint(array);
a.getmean();
}
}
发布于 2018-10-21 02:32:56
问题出在你的构造函数中,
您的构造函数没有正确初始化实例变量int[]数组,因此它保持为空,并在此代码array.length处抛出NullPointerException,
for (int i = 0; i < array.length; i++) { // here array is null so throws NPException
你需要让你的构造器像这样,
public trackint(int[] a) {
array = a;
}
而不是,
public trackint(int[] a) {
a = new int[2];
}
发布于 2018-10-21 02:34:21
public trackint(int[] a){
a = new int[2];
}
这是重新分配a
局部变量。相反,您应该这样做
public trackint(int[] a){
array = a;
}
这会将array
设置为a
的值。
不过,我还没有测试过这个。所以,如果你在回答中遇到任何问题,请在下面评论。
发布于 2018-10-21 02:37:35
您必须初始化array
public trackint(int[] a){
array = a;
}
或
public trackint(int[] a) {
array = new int[a.length];
System.arraycopy(a, 0, array, 0, a.length);
}
或者直接将数组传递给getmean函数。
https://stackoverflow.com/questions/52908811
复制相似问题