import java.util.ArrayList;
public class SimpleDotCom {
private ArrayList locationCells;
public void setLocationCells(ArrayList loc) {
locationCells = loc;
}
public String checkYourself(String userinput) {
int index = locationCells.indexOf(userinput);
String result = "miss";
if(index >= 0){
locationCells.remove(index);
if(locationCells.isEmpty()) {
result = "kill";
}else{
result = "hit";
}
}
System.out.println(result);
return result;
}
}
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("enter a number");
String result = theDotCom.checkYourself(guess);
numOfGuesses++;
if(result.equals("kill")) {
isAlive = false;
System.out.println("You took " + numOfGuesses + " guesses");
}
}
}
}
报错显示为:Exception in thread "main" java.lang.Error: Unresolved compilation problem:
The method setLocationCells(ArrayList) in the type SimpleDotCom is not applicable for the arguments (int[])
at SimpleDotComGame.main(SimpleDotComGame.java:12)
求大佬解答
兄弟!我看了看,你的意思是随机生成3个连续的数可能是【0,1,2】【1,2,3】.....【4,5,6】等等。然后你自己手动输入一个数,判断这个输入的数是否在随机生成的3个数中,如果是的话,把输入的数从集合中删除,并打印“hit”,否则打印“miss”.
我亲手测了一下没问题了。
首先1,你不能i传个nt[]数组类型进去,其次还有其他问题,你创建集合必须用泛型《string》,这样你添加进去的元素是string,才能调用indexof方法
代码如下:
如果有问题找我。。我是为积分来的
setLocationCells方法需要ArrayList类型,你怎么传个int[]数组类型进去。
你需要吧int[]转成ArrayList:
转成ArrayList locations = new ArrayList<>();
locations.add(randomNum);
localtions.add(randomNum + 1);
localtions.add(randomNum + 2);
传参数错误
int[] locations = {randomNum, randomNum + 1, randomNum + 2};
变为
ArrayList locations = new ArrayList();
locations.add(randomNum);
locations.add(randomNum + 1);
locations.add(randomNum + 2);
类型传错了,不能用int[]!!
public void setLocationCells(ArrayList loc) {
locationCells = loc;
}
int[] locations = {randomNum, randomNum + 1, randomNum + 2};
此处需要将int[]ArrayList locations = new ArrayList<>();
locations.add(randomNum);
localtions.add(randomNum + 1);
localtions.add(randomNum + 2);