這兩天準(zhǔn)備把java的基礎(chǔ)重新看一下,剛好看到之前只看了一個(gè)開(kāi)頭的斯坦福的編程方法學(xué)的視頻,于是就重新開(kāi)始從頭看起。
剛看了第一章,收獲還是蠻大的。老師講到編程的重點(diǎn)不在于語(yǔ)言,而在于思想。好比一個(gè)人只知道語(yǔ)言的詞匯和語(yǔ)法,他是無(wú)法寫(xiě)出好文章的。所以,老師利用一個(gè)小的工具--karel來(lái)讓同學(xué)入門(mén),著重于編程的思想,不讓java的語(yǔ)言特性分心。不得不說(shuō),斯坦福的教學(xué)理念確實(shí)很先進(jìn)。
在老師的例子中,強(qiáng)調(diào)的是自頂向下的設(shè)計(jì)方法,要完成一個(gè)任務(wù),需要將一個(gè)大任務(wù)分解為一個(gè)一個(gè)的小任務(wù),再將小任務(wù)繼續(xù)分解,直到每個(gè)任務(wù)都解決一個(gè)問(wèn)題為止
- solve a problem
- methods (1-15 lines)
- good names
- comments
以下是karel編程第一題的解決方法
/*
* File: CollectNewspaperKarel.java
* --------------------------------
* At present, the CollectNewspaperKarel subclass does nothing.
* Your job in the assignment is to add the necessary code to
* instruct Karel to walk to the door of its house, pick up the
* newspaper (represented by a beeper, of course), and then return
* to its initial position in the upper left corner of the house.
*
* author:zhendongYi
* 2016/06/27
*/
import stanford.karel.*;
public class CollectNewspaperKarel extends SuperKarel {
/*
* 主方法
* @see stanford.karel.SuperKarel#run()
*/
public void run(){
CollectNewspaper(); //取報(bào)紙
GoBack(); //返回
}
/*
* 取報(bào)紙
*/
private void CollectNewspaper() {
GoWithFloor(); //沿著天花板走
GoWithWall(); //沿著墻走
PickNewspaper(); //撿報(bào)紙
}
/*
* 沿著墻走
*/
private void GoWithWall() {
while(leftIsBlocked()){ //前進(jìn)
move();
}
turnLeft(); //右轉(zhuǎn)
}
/*
* 沿著天花板走
*/
private void GoWithFloor() {
while(frontIsClear()){ //前進(jìn)
move();
}
turnRight(); //右轉(zhuǎn)
}
private void PickNewspaper() {
move();
pickBeeper();
}
private void GoBack() {
turnAround();
while(frontIsClear()){
move();
}
turnRight();
move();
}
}