JAVA 關於void裡的return指令

2014-08-11 8:38 am
請問在void裡面的return指令有什麼用途
這個是河內之塔遊戲的解法一部份
------------------------------------------------------------------------
class HanoiTowerGame {

void go(int discs) {
hanoiTower('A', 'C', 'B', discs);
}

void moveDisc(char source, char target, int disc) {
System.out.println("Move No." + disc + " disc from " + source + " to " + target);
}

void hanoiTower(char a, char c, char b, int discs) {
System.out.println("discs = " + discs);
if(discs == 1) {
moveDisc(a, c, discs);
return;
}

hanoiTower(a, b, c, discs - 1);
moveDisc(a, c, discs);
hanoiTower(b, c, a, discs - 1);
}
}
------------------------------------------------------------------------
說明上所指這個指令是為了跳出控制區塊
但小弟不明白用意
希望可以詳細講解一下
謝謝!!!

回答 (1)

2014-08-11 11:03 am
✔ 最佳答案
void hanoiTower(char a, char c, char b, int discs)
{
System.out.println("discs = " + discs);
if(discs == 1)
{
moveDisc(a, c, discs);
return;
}
hanoiTower(a, b, c, discs - 1);
moveDisc(a, c, discs);
hanoiTower(b, c, a, discs - 1);
}

解釋:
如果(discs == 1) 就 moveDisc(a, c, discs), 然後離開;
但如果不是(discs == 1),就會繼續執行其餘的程式:
hanoiTower(a, b, c, discs - 1);
moveDisc(a, c, discs);
hanoiTower(b, c, a, discs - 1);

2014-08-11 12:33:28 補充:
Process Discs - 3
Process Discs - 2
Process Discs - 1
Move No.1 disc from a to c
Move No.2 disc from a to b
Process Discs - 1
Move No.1 disc from c to b
Move No.3 disc from a to c
Process Discs - 2
Process Discs - 1
Move No.1 disc from b to a
Move No.2 disc from b to c
Process Discs - 1
Move No.1 di

2014-08-11 12:47:08 補充:
其實這是一個recursive program,過程應該是由disc3開始,因為不是Disc1,所以excute:
hanoiTower(a, b, c, discs - 1);
Disc3就變成Disc2,再變成Disc1,然後excute "if statement"的指令Move No.1 disc from a to c. 因為係recursive program,所以當去到return,就回到moveDisc(a, c, discs);

2014-08-11 13:02:01 補充:
這時係Disc2,然後又call - hanoiTower(b, c, a, discs - 1);變成Disc1,excute "if statement"的指令.
如果你留意到 hanoiTower(a, b, c, discs - 1);同hanoiTower(b, c, a, discs);內的a,b,c 係在不同位置,影響放置disc的位置.在2014-08-11 16:33:23 補充,可見steps output.

2014-08-11 13:21:59 補充:
Sorry,因字數有限,要多次補充


收錄日期: 2021-04-15 16:07:35
原文連結 [永久失效]:
https://hk.answers.yahoo.com/question/index?qid=20140811000051KK00007

檢視 Wayback Machine 備份