P95
《Head First Java》20200904读书笔记
第五章 编写程序
高层设计
游戏的简单版
程序的编写:
- 找出类应该做的事
- 列出实例变量和方法
- 编写方法的伪码
- 编写方法的测试用程序
- 实现类
- 测试方法
- 除错或重新设计
每个类的编写:
- 编写伪码
- 编写测试码
- 编写真实码
伪码:实例变量的声明、方法的声明、方法的逻辑
测试码:先写出测试用的部分
class SimpleDotComTestDrive
package SimpleDotComGame;
public class SimpleDotComTestDrive {
public static void main (String[] args) {
SimpleDotCom dot = new SimpleDotCom();
int[] locations = {2,3,4};
dot.setLocationCells(locations);
String userGuess = "2";
String result = dot.checkYourself(userGuess);
}
}
class SimpleDotCom
package SimpleDotComGame;
public class SimpleDotCom {
int[] locationCells;
int numOfHits = 0;
public void setLocationCells(int[] locs) {
locationCells = locs;
}
public String checkYourself(String stringGuess) {
int guess = Integer.parseInt(stringGuess);
String result = "miss";
for (int cell : locationCells) {
if (guess == cell) {
result = "hit";
numOfHits++;
break;
}
}
if (numOfHits == locationCells.length) {
result = "kill";
}
System.out.println(result);
return result;
}
}
结果:
class GameHelper
package SimpleDotComGame;
import java.io.*;
public class GameHelper {
public String getUserInput(String prompt) {
String inputLine = null;
System.out.print(prompt + " ");
try {
BufferedReader is = new BufferedReader(new InputStreamReader(System.in));
inputLine = is.readLine();
if(inputLine.length() == 0 ) return null;
}catch (IOException e){
System.out.println("IOException:" + e);
}
return inputLine;
}
}
class SimpleDotComGame
package SimpleDotComGame;
public class SimpleDotComGame {
public static void main(String[] args) {
int numOfGuesses = 0;
GameHelper helper = new GameHelper();
SimpleDotCom theDotCom = new SimpleDotCom();
int randomNum = (int) (Math.random() * 5);
int[] locations = {randomNum,randomNum+1,randomNum+2};
theDotCom.setLocationCells(locations);
boolean isAlive = true;
while(isAlive == true) {
String guess = helper.getUserInput("输入一个数字:");
String result = theDotCom.checkYourself(guess);
numOfGuesses++;
if(result.equals("kill")) {
isAlive = false;
System.out.println("You took" + numOfGuesses + "guesses");
}
}
}
}
结果: