如何从null私有函数内部构建数组?

时间:2019-01-06 12:09:43

标签: java arrays function recursion multidimensional-array

我试图在私有函数中构建从公共函数获取空数组的数组,我从公共函数调用私有函数,然后尝试制作arr[i][j] = 1,然后将递归添加到int j +1,但是当我执行arr[i][j] = 1时,出现运行时错误:NullPointerException,我不知道arr[0].length,我只知道arr.length是n,可以解决吗?

public static int howManySorted(int n, int max) 
{
     int i = 0;
     int j = 0;
     boolean first = false;
     int count = 0;
     int[][] arr = new int[n][];



     return howManySorted(n,max,arr,i,j,first,count);
}
private static int howManySorted(int n,int max,int[][] arr,int i,int j,boolean first,int count)
{
    if(n < 1)
        return 0;

    if(j < n)
    {
        arr[i][j] = 1;
        count++;
        first = true;
        return howManySorted(n,max,arr,i,j+1,first,count);
    }

2 个答案:

答案 0 :(得分:0)

通过修改代码行

消除了异常
<?php

/**
 * Gets the contents of the Create React App manifest file
 *
 * @return array|bool|string
 */
function get_app_manifest() {
    $manifest = file_get_contents( get_template_directory_uri() . '/assets/app/build/asset-manifest.json' );
    $manifest = (array) json_decode( $manifest );

    return $manifest;
}

/**
 * Gets the path to the stylesheet compiled by Create React App
 *
 * @return string
 */
function get_app_stylesheet() {
    $manifest = get_app_manifest();

    return get_template_directory_uri() . '/assets/app/build/' . $manifest['main.css'];
}

/**
 * Gets the path to the built javascript file compiled by Create React App
 *
 * @return string
 */
function get_app_script() {
    $manifest = get_app_manifest();

    return get_template_directory_uri() . '/assets/app/build/' . $manifest['main.js'];
}

/**
 * Enqueues the scripts
 */
add_action( 'wp_enqueue_scripts', function() {
    enqueue_react_app();
} );

/**
 * Enqueues the stylesheet and js
 */
function enqueue_react_app() {
    wp_enqueue_script( 'graphql-workshop', get_app_script(), array(), false, true );
    wp_enqueue_style( 'graphql-workshop', get_app_stylesheet(), array(), false, false );
}


int[][] arr = new int[n][];

当您执行int[][] arr = new int[n][n]; 时,它会创建一个new int[n][]的数组,而执行nulls就像执行arr[i][j]一样会导致null[j]

或者,您也可以这样做,

NullPointerException

在做

之前
arr[i] = new int[10];  // initialize internal array 

答案 1 :(得分:0)

像这样初始化的数组

int[][] arr = new int[n][];

尚未完全初始化,因此无法将值分配给单元格。 此定义等于以下内容:“将每个单元格定义为一个数组的数组”,因此每个单元格也需要初始化(它的大小不必相同) 您需要像这样完全初始化数组的数组:

int[][] arr = new int[n][n];  // a nxn sized matrix

或者,您也可以像这样分别初始化每一行:

arr[0] = new int[n];  // initialized one cell of arr