想要多维数组,但获得空指针异常 [英] Want a multidimensional array but get a null pointer exception
本文介绍了想要多维数组,但获得空指针异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
1 public class TestWin{
2 public static void main(String[] args){
3 int n;
4 hexagon[][] board;
5
6 n = 4;
7 board = new hexagon[n][n];
8 board[0][0].value = 'R';
嗨.javac不喜欢我在第8行上所做的事情.有人知道为什么吗?
Hi. javac doesn't like what I did on line 8. Does anyone know why?
推荐答案
kwatford上的现货.您在第7行所做的只是告诉Java在二维数组中为n * n个Hexagon对象创建空间.
Spot on kwatford. All you have done with line 7 is to tell java to create space for n*n Hexagon objects in a 2 dimensional array.
您仍然需要为每个这些六边形调用新的
You will still need to call new for each of these Hexagons
本质上,您需要将第7行替换为以下内容:
Essentially, you need to replace line 7 with something like:
board = new Hexagon[n][n];
for(int i=0; i<n; i++)
for(int j=0; j<n; j++)
board[i][j] = new Hexagon();
这篇关于想要多维数组,但获得空指针异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文