【发布时间】:2017-06-29 17:49:20
【问题描述】:
好吧...所以我已经被学校的练习卡住了一段时间,我真的不知道如何解决它。我想我已经和我开始的地方相比真的来了,我希望你们能帮助我。
该练习的最终含义是代码将输出数组中每个数字的所有可能邻居。我已经完成了中间四个,它们工作得很好。外面的数字对我来说很痛苦,我找不到确保让代码“注意到”没有更多数字的方法,例如,在左上角的数字上方。
我觉得我知道该怎么做:如果数组的索引值高于 3 或低于 0,则使用 if 语句不会让事情发生。因为它是一个 4x4 2D 数组,这意味着X轴和Y轴有0、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 {
}
}
}
}
}
【问题讨论】:
-
我想你想要这样的东西:
if((i - 1 > -1 && i + 1 < 4) && (j - 1 > -1 && j + 1 < 4)) -
您的问题不清楚。您想要直接邻居还是 2 方格外的邻居?
-
每个数字周围的邻居。
标签: java arrays if-statement for-loop multidimensional-array