import java.util.Scanner;
import java.util.ArrayList;
class SimpleDotcomtestDrive {//测试开发代码
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
SimpleDotcom dot = new SimpleDotcom();
int randomNum = (int)(Math.random()*10);//产生任意数
int n =1;
ArrayList<String> location = new ArrayList<String>();//建立arraylist
String a = new String(" "+(randomNum+1));/*储存正确答案*/
location.add(a);
String b = new String(""+(randomNum+2));
location.add(b);
String c = new String(""+(randomNum));
location.add(c);
dot.setlocationcells(location); //设置
System.out.println("请输入一个0到10的数字: ");
String user_Guess = scanner.nextLine();//输入数字
String result =dot.checkYouself(user_Guess);
while(true){
if(result.equals("kill")){
System.out.println("You took "+ n +" guesses");
break;
}else{
System.out.println("请输入一个0到10的数字: ");
String user_Guess00 = scanner.nextLine();
n=++n;
result = dot.checkYouself(user_Guess00);
}
}
}
}
/*实际代码*/
public class SimpleDotcom {
private ArrayList<String> locationcells;
public void setlocationcells(ArrayList<String> loc) {
locationcells = loc;//获取值
}
public String checkYouself(String a){
int guess = Integer.parseInt(a);//将字符串转化为数字
int index = locationcells.indexOf(guess);//返回a的位置
String result ="miss";//初始胡result
if(index>=0){ //有匹配的数
locationcells.remove(index); //删除匹配数字
if(locationcells.isEmpty()){
result = "kill";
}else {
result = "hit";
}
}
System.out.println(result);
return result;
}
}
结果问题就是好像没有正确答案,我DEbug的时候发现传输arraylist到另一个对象的时候,字符串消失了,好像这样不能传一样,不管我猜啥数字都无法猜中正确答案。