如何初始化一个二维阵列

如何初始化一个二维阵列

本文介绍了如何初始化一个二维阵列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

public class example
{
    static class point
    {
        int x;
        int y;
    }

    static void main(String args[])
    {
        point p = new point();
        point[] p1 = new point[5];
        point[][] p2 = new point[5][5];

        p.x = 5; //No problem
        p[0].x = 5; //When I run the program, it gives error:java.lang.NullPointerException
        p[0][0].x = 5; //When I run the program, it gives error:java.lang.NullPointerException
    }

我怎么能初始化P [],X和P [] [],X?

How can I initialize p[].x and p[][].x?

推荐答案

您需要手动初始化整个数组和各级,如果多层次的:

You need to manually initialize the whole array and all levels if multi-leveled:

point[] p1 = new point[5];
// Now the whole array contains only null elements

for (int i = 0; i < 5; i++)
  p1[i] = new point();

p1[0].x = 1; // Will be okay

这篇关于如何初始化一个二维阵列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-19 12:00