明确地将值分配给2D数组? [英] Explicitly assigning values to a 2D Array?

查看:117
本文介绍了明确地将值分配给2D数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我以前从未这样做过,也找不到答案。这可能不是用于此的正确数据类型,但我只想分配一个int,然后另一个没有for循环的int进入2D数组,这些值实际上是从另一个函数返回的,但为了简单起见,我已经刚用过int i和k,这就是我认为你做的,但不是:

  int contents [] [] = new int [2] [2]; 
contents [0] [0] = {int i,int k}
contents [1] [1] = {int i,int k}
contents [2] [2] = {int i,int k}

TIA - 随时指向更好的数据方向如果我正在咆哮错误的树,请执行此操作。

解决方案

最好的方法可能是一次声明并分配所有值。如此处所示。
Java将自动确定数组的大小,并将值分配给这样。

  int contents [] [] = {{1,2},{4,5}}; 

或者,如果您需要先声明数组,请记住每个内容[ 0] [0] 指向单个整数值而不是两个数组。所以要得到与上面相同的作业,你会写:

  contents [0] [0] = 1; 
内容[0] [1] = 2;
内容[1] [0] = 4;
内容[1] [1] = 5;

最后我要注意2乘2阵列的索引是0到1而不是0到2。 / p>

希望有所帮助。


I've never done this before and can't find the answer. This may not be the correct data type to use for this, but I just want to assign an int, then another int without a for loop into a 2D array, the values will actual be returns from another function, but for simplicity I've just used int i and k, this is how I thought you'd do it, but its not:

int contents[][] = new int[2][2];
            contents[0][0] = {int i, int k}
            contents[1][1] = {int i, int k}
            contents[2][2] = {int i, int k}

TIA - feel free to point me in the direction of a better data struct to do this if I'm barking up the wrong tree.

解决方案

The best way is probably to just declare and assign all values at once. As shown here. Java will automatically figure out what size the array is and assign the values to like this.

int contents[][] = { {1, 2} , { 4, 5} };

Alternatively if you need to declare the array first, remember that each contents[0][0] points to a single integer value not an array of two. So to get the same assignment as above you would write:

contents[0][0] = 1;
contents[0][1] = 2;
contents[1][0] = 4;
contents[1][1] = 5;

Finally I should note that 2 by 2 array is index from 0 to 1 not 0 to 2.

Hope that helps.

这篇关于明确地将值分配给2D数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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