填充数组时出现java.lang.NullPointerException [英] java.lang.NullPointerException when filling array

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

问题描述

目标:通过随机数和排序数创建x大小的数组.

The goal: create array with x size by random numbers and sort numbers.

Array.java

import java.util.Random;

/**
 * Created by cazorla19 on 05.03.16.
 */
public class Array {

    int myArray[];
    Random rand;

    Array() {
    }

    Array (int x) {
        Array myArray[];
        myArray = new Array[x];
        for (int i=0; i<x; i++) {
            myArray[i] = new Array();
        }
    }

    int[] ArrayFill () {
        for (int i=0; i<myArray.length; i++) {
            int j = rand.nextInt();
            myArray[i] = j;
        }
        return myArray;
    }

    int[] ArraySort (){
        System.out.println ("Here is the Bubble sort!");
        for (int i=0; i<myArray.length; i++) {
            for (int j=0; j<myArray.length - i - 1; j++) {
                if (myArray[j] > myArray[j+1]) {
                    int temp = myArray[j];
                    myArray[j] = myArray [j+1];
                    myArray[j+1] = temp;
                }
            }
        }
        return myArray;
    }

    void ArrayPrint() {
        for (int i=0; i<myArray.length; i++) {
            System.out.print (myArray[i] + ", ");
        }
    }

}

ArrayDo.java

ArrayDo.java

/**
 * Created by cazorla19 on 05.03.16.
 */
public class ArrayDo extends Array {

    public static void main (String args[]) {
        int x = 10;
        Array labArray = new Array(x);
        labArray.ArrayFill();
        labArray.ArrayPrint();
        labArray.ArraySort();
        labArray.ArrayPrint();
    }
}

有点例外.

Exception in thread "main" java.lang.NullPointerException
    at Array.ArrayFill(Array.java:23)
    at ArrayDo.main(ArrayDo.java:10)

那是我尝试使用数组长度的地方.试图解决这个问题[1][2].尽管我在数组构造函数中做了,但我认为我无法从 NULL 更改数组值.有没有人强迫过类似的问题?我知道这应该很容易,但仍然无法意识到哪里出了问题.

That's where I tried to use length of array. Tried to figured out through this issues [1][2]. It's thought I can't change array values from NULL despite of I did in array constructor. Did anyone force with similar issue? I know it should be pretty easy, but still can't realize what's wrong.

推荐答案

初始化下面的值,你应该很高兴!

Initialize the below values and you should be good to go!

int myArray[]=new int[10];
Random rand=new Random();

这篇关于填充数组时出现java.lang.NullPointerException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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