[英]Neighbors in a 2D 4x4 Array
好吧...所以我已经被学校练习困住了一段时间,我真的不知道如何解决它。 我认为与我开始的地方相比,我真的来了,我希望你们能帮助我。
练习的最终含义是代码将输出数组中每个数字的所有可能的邻居。 我已经完成了中间的四个,它们完美地工作。 外部数字对我来说很痛苦,我找不到一种方法来确保代码“注意”没有更多数字,例如,在左上角的数字上方。
我觉得我知道该怎么做:如果数组的索引值高于 3 或低于 0,则使用 if 语句不会发生任何事情。因为它是一个 4x4 2D 数组,这意味着有 0 X 轴和 Y 轴的 , 1, 2, 3 索引。
我希望这里有人愿意帮助我。 将不胜感激! 到目前为止,这是我的代码!
提前致谢
public class P620 {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
int[][] counts =
{
{ 1, 0, 3, 4},
{ 3, 5, 6, 4 },
{ 9, 7, 1, 4},
{ 1, 1, 1, 1}
};
for(int i = 0; i <= 3; i++) {
for(int j = 0; j <= 3; j++) {
System.out.println("Neighbours van de array: " + i + j + " met waarde: " + counts[i][j]);
if ((i < 4 && i > -1) && (j < 4 && j > -1)) {
System.out.println(counts[i - 1][j]);
}
else if ((i < 4 && i > -1) && (j < 4 && j > -1)) {
System.out.println(counts[i - 1][j - 1]);
}
else if ((i < 4 && i > -1) && (j < 4 && j > -1)) {
System.out.println(counts[i - 1][j + 1]);
}
else if ((i < 4 && i > -1) && (j < 4 && j > -1)) {
System.out.println(counts[i][j - 1]);
}
else if ((i < 4 && i > -1) && (j < 4 && j > -1)) {
System.out.println(counts[i + 1][j - 1]);
}
else if ((i < 4 && i > -1) && (j < 4 && j > -1)) {
System.out.println(counts[i + 1][j]);
}
else if ((i < 4 && i > -1) && (j < 4 && j > -1)) {
System.out.println(counts[i + 1][j + 1]);
}
else if ((i < 4 && i > -1) && (j < 4 && j > -1)) {
System.out.println(counts[i][j + 1]);
}
else {
}
}
}
}
}
这里有一个小提示:
for (int i=0; i < 4; ++i) {
for (int j=0; j<4; ++j) {
System.out.println("Neighbours van de array: " + i + j + " met waarde: " + counts[i][j]);
// print upper-left (northwest) neighbor, if there is one
if (i >= 1 && j >= 1)
System.out.println(counts[i-1][j-1]);
// print upper (north) neighbor, if there is one
if (i >= 1)
System.out.println(counts[i-1][j]);
.
.
.
// print lower (south) neighbor, if there is one
if (i < 3)
System.out.println(counts[i+1][j]);
// print lower-right (southeast) neighbor, if there is one
if (i < 3 && j < 3)
System.out.println(counts[i+1][j+1]);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.