潜水望远镜 2016-04-16 15:03 采纳率: 0%
浏览 1320

NullPointerException

public class RandomArray {
private int arraySize;
private int sum;
private double average;
private int[] array; // instance variable
/**
* Constructor
* @param size The size of the array.
*/
public RandomArray(int size) {
// write your code here
arraySize = size;
int[] array = new int[arraySize];
for (int i = 0; i < arraySize; i++) {
array[i] = (int) Math.random()*10;
}
}

/**
 *  A method to print the array elements.
 */
public void printArray() {
    // write your code here
    for(int i = 0; i < arraySize; i++)
        System.out.print(array[i]);
}

/**
 *  A method to calculate the sum of all elements.
 *  @return  The sum.
 */
public int calcSum() {
    // write your code here
    sum = 0;
    for(int i = 0; i < arraySize; i++)
        sum += array[i];
    return sum;
}

/**
 *  A method to calculate the mean (or average) of all elements.
 *  @return  The mean.
 */
public double calcMean() {
    // write your code here
    average = this.calcSum() / arraySize;
    return average;
}

/**
 *  A main method to test.
 */
public static void main(String[] args) {
    // Check to see if the user has actually sent a parameter to the method.
    if (args.length != 1) {
        System.out.println("Usage: java RandomArray <NUM>. Example: java RandomArray 5");
    System.exit(-1);
}

// Create an instance of the class.
RandomArray test = new RandomArray(Integer.parseInt(args[0]));

// Print the array.
test.printArray();

// Calculate the sum of all the values in the array and print it.
System.out.println("Sum: " + test.calcSum());

// Calculate the mean of all the values in the array and print it.
System.out.println("Mean: " + test.calcMean());
}

}

错误报告
Exception in thread "main" java.lang.NullPointerException
at RandomArray.printArray(RandomArray.java:35)
at RandomArray.main(RandomArray.java:74)

  • 写回答

2条回答

  • threenewbee 2016-04-16 15:07
    关注

    sum += array[i];
    这里array在哪里定义的?哪里初始化的?

    评论

报告相同问题?

悬赏问题

  • ¥20 Python安装cvxpy库出问题
  • ¥15 用前端向数据库插入数据,通过debug发现数据能走到后端,但是放行之后就会提示错误
  • ¥15 python天天向上类似问题,但没有清零
  • ¥30 3天&7天&&15天&销量如何统计同一行
  • ¥30 帮我写一段可以读取LD2450数据并计算距离的Arduino代码
  • ¥15 C#调用python代码(python带有库)
  • ¥15 矩阵加法的规则是两个矩阵中对应位置的数的绝对值进行加和
  • ¥15 活动选择题。最多可以参加几个项目?
  • ¥15 飞机曲面部件如机翼,壁板等具体的孔位模型
  • ¥15 vs2019中数据导出问题