Head First Java p.139 Battleships ArrayList<>问题

时间:2018-06-04 11:39:06

标签: java arraylist

我是一个想要学习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>;

这解决了异常并且程序将运行但是在命令行中输入猜测不会返回“Hit,Miss或Kill”值,我可以猜出任何数字。换句话说,战舰游戏不起作用。

供您参考,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章我真的很难自己想出可用的代码行,但是我希望这对于几乎没有经验的人来说是正常的吗?我也担心其他任何人都不会问这个问题!

1 个答案:

答案 0 :(得分:0)

您似乎必须使用新方法覆盖现有方法setLocationCells,并接受int[] loc。此外,最好在locationCells内隐藏DotCom以排除在此类之外的修改。

class DotCom {

    private final List<String> locationCells = new ArrayList<>();

    public void setLocationCells(List<String> loc) {
        locationCells.clear();

        if (loc != null)
            locationCells.addAll(loc);
    }

    public void setLocationCells(int[] loc) {
        locationCells.clear();

        if(loc != null)
            for(int val : loc) 
                locationCells.add(String.valueOf(val));
    }

}

如果您无法修改DotCom,则可以使用int[]在客户端将ArrayList<String>转换为Stream

TheDotCom.setLocationCells((ArrayList<String>)Arrays.stream(locations).boxed().map(String::valueOf).collect(Collectors.toList()));

<强> P.S。 在您的示例中,您甚至不必将int[]转换为ArrayList<String>,因为您可以创建ArrayList<String>而不是int[],尤其是当您只有3时这个数组中的值。

public static void main(String... args) throws IOException {
    GameHelper helper = new GameHelper();
    DotCom dotCom = new DotCom();

    // create and add locations using random generator
    int rnd = (int)(Math.random() * 5);
    dotCom.setLocationCells(new ArrayList<>(Arrays.asList(String.valueOf(rnd), String.valueOf(rnd + 1), String.valueOf(rnd + 2))));

    boolean alive = true;
    int numOfGuesses = 0;

    while (alive) {
        String result = dotCom.checkYourself(helper.getUserInput("enter a number"));
        numOfGuesses++;

        if ("Kill".equals(result)) {
            alive = false;
            System.out.println("You took " + numOfGuesses + " guesses, to" + "destroy the DotCom");
        }
    }
}