潜水望远镜 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在哪里定义的?哪里初始化的?

    评论

报告相同问题?

悬赏问题

  • ¥15 C#读写EXCEL文件,不同编译
  • ¥15 如何提取csv文件中需要的列,将其整合为一篇完整文档,并进行jieba分词(语言-python)
  • ¥15 MapReduce结果输出到HBase,一直连接不上MySQL
  • ¥15 扩散模型sd.webui使用时报错“Nonetype”
  • ¥15 stm32流水灯+呼吸灯+外部中断按键
  • ¥15 将二维数组,按照假设的规定,如0/1/0 == "4",把对应列位置写成一个字符并打印输出该字符
  • ¥15 NX MCD仿真与博途通讯不了啥情况
  • ¥15 win11家庭中文版安装docker遇到Hyper-V启用失败解决办法整理
  • ¥15 gradio的web端页面格式不对的问题
  • ¥15 求大家看看Nonce如何配置