2 baidu 34135035 baidu_34135035 于 2016.04.16 23:03 提问

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)

3个回答

caozhy
caozhy   Ds   Rxr 2016.04.16 23:07

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

caozhy
caozhy   Ds   Rxr 2016.04.16 23:09

你的程序args[0]是什么,你有传命令行参数给程序么?

参照 http://blog.csdn.net/randomnet/article/details/7416456
这里的做法,给一个参数

baidu_34135035
baidu_34135035 回复baidu_34135035: 已解决,多谢
一年多之前 回复
baidu_34135035
baidu_34135035 array定义在Random类里,命令行参数给了
一年多之前 回复
CSDNXIAOD
CSDNXIAOD   2016.04.16 23:12

onStartCommand NullPointerException
----------------------biu~biu~biu~~~在下问答机器人小D,这是我依靠自己的聪明才智给出的答案,如果不正确,你来咬我啊!

Csdn user default icon
上传中...
上传图片
插入图片
准确详细的回答,更有利于被提问者采纳,从而获得C币。复制、灌水、广告等回答会被删除,是时候展现真正的技术了!