【发布时间】:2018-11-13 17:43:30
【问题描述】:
我是一名想要学习 Java 的菜鸟。我正在阅读“Head First Java”一书并非常喜欢它。在学习使用ArrayList<> 而不是常规的array[] 时,我遇到了一个问题。尝试将int[] 分配给ArrayList<> 时出现异常,请参阅以下代码:
import java.util.ArrayList;
public class SimpleDotComGame {
public static void main(String[] args) {
int numOfGuesses = 0;
GameHelper helper = new GameHelper();
DotCom TheDotCom = new DotCom();
int randomNum = (int) (Math.random()*5);
int[] locations = {randomNum, randomNum+1, randomNum+2};
TheDotCom.setLocationCells(locations); <---- Here is the problem.
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, to"
+ "destroy the DotCom");
}
}
}
}
异常如下:
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
The method setLocationCells(ArrayList<String>) in the type DotCom is not applicable for the arguments (int[])
在查找此问题后,我尝试将int[] locations = {} 更改为ArrayList<String>,并使用以下代码发现只有一个人询问过:
ArrayList<String> locations = new ArrayList<String>();
String r1 = Integer.toString(randomNum);
String r2 = Integer.toString(randomNum+1);
String r3 = Integer.toString(randomNum+2);
locations.add(r1);
locations.add(r2);
locations.add(r3); ArrayList<String> locations = new ArrayList<String>;
这解决了异常,程序将运行,但在命令行中输入猜测不会返回“命中、未命中或杀死”值,我可以猜测任何数字。也就是说,战舰这个游戏是不行的。
供您参考,DotCom 类是:
import java.util.ArrayList;
public class DotCom {
private ArrayList<String> locationCells;
// private int numOfHits;
// don't need that now.
public void setLocationCells(ArrayList<String> loc) {
locationCells = loc;
}
public String checkYourself(String userInput) {
String result = "Miss";
int index = locationCells.indexOf(userInput);
if (index >= 0) {
locationCells.remove(index);
if (locationCells.isEmpty()) {
result = "Kill";
} else {
result = "Hit";
}
}
return result;
}
}
您能提供的任何建议都会很棒。我很紧张,在第 5 章我真的很难自己想出可用的代码行,但我希望这对于几乎没有经验的人来说是正常的?我也担心这个问题不是别人问的!
【问题讨论】:
-
locations是int类型的数组,而不是方法要求的ArrayList。这两个人没有太多的关系。ArrayList这个名字只是暗示内部使用了一个数组来保存数据。 -
另外你可能不想对我猜的单元格使用字符串?如果它们只是数字,为什么不使用
Integer? -
裸露在外,但我将您的建议插入如下:ArrayList
locations = Arrays.asList(randomNum, randomNum + 1, randomNum +2);