一个Java项目的正确顺序:
需求分析-流程图--伪代码--测试程序--正式开始写程序的代码。
这个小游戏里面有三个class,名称以及作用如下:
1.SimpleDotComTestDrive:写的第一个程序,测试SimpleDotCom,确保当输入一个数字的时候可以得到正确的结果,在这里面将猜测的三个数字设置为2,3,4.当输入2时观察输出的结果。
2.SimpleDotCom:写的第二个程序,有两个变量,int[] locationCells;数组,记录三个数字, int numOfHits = 0;记录猜中的次数,当次数为三时输出kill
一个方法:public String checkYourself(String stringGuess),判断输入的数字是否是正确的。
3.Game: 从键盘录入输入的字符串,转化为数字,与三个值进行比较,正确则输出hit,否则为miss。
遇到的问题及解决方法:
1.当输入一个数字正确之后再次输入这个数字还会显示正确
解决方法:
当输入一个数字正确之后,把这个数字所对应的位置改为-1,这样就好了。
package FirstGame;,
public class SimpleDotComTestDrive {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
SimpleDotCom dot = new SimpleDotCom();
int[] locations = { 2, 3, 4 };
dot.setLocationCells(locations);
String userGuess = "2";
String result = dot.checkYourself(userGuess);
}
}
public class SimpleDotCom {
int[] locationCells;
int numOfHits = 0;
public void setLocationCells(int[] locs) {
locationCells = locs;
}
public int checkLocation(int cell){
int i;
for (i=0;i<3;i++){
if (locationCells[i]==cell)
return i;
}
return 0;
}
public String checkYourself(String stringGuess) {
int guess = Integer.parseInt(stringGuess);
String result = "miss";
for (int cell : locationCells) {
if ((guess == cell)&&(guess>0)) {
result = "hit";
int t=checkLocation(cell);
locationCells[t]=-1;
numOfHits++;
break;
}
}
if (numOfHits == locationCells.length) {
result = "kill";
}
System.out.println(result);
return result;
}
}
package FirstGame;
import java.io.*;
import java.util.*;
public class Game {
public static void main(String[] args) {
int numOfGuesses = 0;
SimpleDotCom theDotCom = new SimpleDotCom();
int randomNum = (int) (Math.random() * 5);
int[] locations = { randomNum, randomNum + 1, randomNum + 2 };
theDotCom.setLocationCells(locations);
boolean isAlive = true;
System.out.println("Please input a int number");
while (isAlive == true) {
BufferedReader buf = new BufferedReader(new InputStreamReader(System.in));
String guess = null;
try {
guess = buf.readLine();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String result = theDotCom.checkYourself(guess);
numOfGuesses++;
if (result.equals("kill")) {
isAlive = false;
System.out.println("You took " + numOfGuesses + " guesses");
}
}
}
}