[英]Lines of Action board with recursive
我一直在嘗試以遞歸方式制作“行動綱領”委員會。 我已經完成了多維數組(8x8)。 現在,我唯一的問題是如何將碎片放置在正確的位置(尤其是黑色的碎片)。 我怎么了 當我嘗試打印作品的第一行時,它會打印如下內容: "-bbbbb--"
,而不是"-bbbbbb-"
。 最后一行也是如此。
public static void im (int[][]m, int r, int c){//Matriz
if (r==m.length-1 && c==m[0].length-1) {
System.out.print("-");
} else {
if(r==0 && c>0 && c<m[0].length-1){
System.out.print("b");
}
if(c==0 && r>0 && r<m.length-1){
System.out.print("w");
}
if (c==m[0].length-1) {
if(r>0){
System.out.print("w");
System.out.println("");
im(m,r+1,0);
}else{
System.out.print("-");
System.out.println("");
im(m,r+1,0);
}
} else {
System.out.print("-");
im(m,r,c+1);
}
}
}
if語句中的邏輯有缺陷,您可以重試並在每個塊中添加注釋,直到現在為止。 像這樣:
if (a) {
// I know that a == true
if (b) {
// I know that a == true && b == true
} else {
// I know that a == true && b == false
}
}
這樣,您便可以輕松地發現自己的錯誤,如果這樣做不能幫助您進行注釋,我會回復正確的代碼。
編輯:這是正確的代碼:
if (r == 0 || r == m[0].length - 1) {
// top or bottom row
if (c == 0 || c == m.length - 1) {
// top or bottom row and leftmost column or rightmost column
System.out.print("-");
} else {
// top or bottom row and not leftmost column or rightmost column
System.out.print("b");
}
} else {
// not top or bottom row
if (c == 0 || c == m.length - 1) {
// not top or bottom row and leftmost column or rightmost column
System.out.print("w");
} else {
// not top or bottom row and not leftmost column or rightmost column
System.out.print("-");
}
}
我真的不知道如何解決您的原始代碼,因為這對我來說真的沒有意義,所以我完全重寫了它,要記住的一件好事是,您希望每個函數調用僅輸出1個字符,因此至少嘗試確保它一次只能到達其中一個打印語句。
編輯2:
public static void im(int[][] m, int r, int c) {
if (r == 0 || r == m.length - 1) {
// top or bottom row
if (c == 0 || c == m[0].length - 1) {
// top or bottom row and leftmost column or rightmost column
System.out.print("-");
} else {
// top or bottom row and not leftmost column or rightmost column
System.out.print("b");
}
} else {
// not top or bottom row
if (c == 0 || c == m[0].length - 1) {
// not top or bottom row and leftmost column or rightmost column
System.out.print("w");
} else {
// not top or bottom row and not leftmost column or rightmost column
System.out.print("-");
}
}
if (c == m[0].length - 1) {
// rightmost column
System.out.println();
if (r != m.length - 1) {
// not bottom row
im(m, r + 1, 0);
}
} else {
// not rightmost column
im(m, r, c + 1);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.