NullPointerException对象和数组 [英] NullPointerException object and arrays

查看:72
本文介绍了NullPointerException对象和数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

public class SearchComparison {
    StopWatch watch = new StopWatch();
    ArrayUtilities utilities = new ArrayUtilities();

    public void main(String[] args){    
        watch.start();
        utilities.generateRandom(5);
        watch.stop();
    }
}

我正在尝试运行此代码,但它给出了我出现了NullPointerException错误。但是,我使用的方法似乎可以单独使用。有人可以帮我指出我的错误吗?
预先谢谢您!

I'm trying to run this code but it gives me a NullPointerException error. However, the methods I'm using seem to work fine separately. Can someone help me pointing out my mistake? Thank you in advance!

以下是有问题的方法:

public class StopWatch {
    private long startTime;
    private long stopTime;

    public long start(){
        startTime = System.nanoTime();
        return startTime;
    }
    public long stop(){
        stopTime = System.nanoTime();
        return stopTime;
    }
}

public class ArrayUtilities {
    public static int[] generateRandom(int n){
        Random r = new Random(1);
        int imax = Integer.MAX_VALUE;
        int[] array = new int[n];
        for(int i = 0; i < n; i++){
            array[i] = r.nextInt(imax);
            System.out.println(array[i]);
        }
        return array;
    }
}


推荐答案

方法缺少修饰符 static

应为 public static void main(String [] args){

按如下所示更改类 SearchComparison 的代码,您将获得正确的结果。

Change your code of class SearchComparison as follows and you will get the right result.

public class SearchComparison {

public static void main(String[] args) {
    StopWatch watch = new StopWatch();
    ArrayUtilities utilities = new ArrayUtilities();
    watch.start();
    utilities.generateRandom(5);
    watch.stop();
}

}

一次运行的结果为

1569548985
215764588
880641847
874970313
446064254

这篇关于NullPointerException对象和数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆