[英]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.