【问题标题】:Head First Java p.139 Battleships ArrayList<> IssueHead First Java p.139 Battleships ArrayList<> 问题
【发布时间】:2018-11-13 17:43:30
【问题描述】:

我是一名想要学习 Java 的菜鸟。我正在阅读“Head First Java”一书并非常喜欢它。在学习使用ArrayList&lt;&gt; 而不是常规的array[] 时,我遇到了一个问题。尝试将int[] 分配给ArrayList&lt;&gt; 时出现异常,请参阅以下代码:

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&lt;String&gt;,并使用以下代码发现只有一个人询问过:

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

【问题讨论】:

  • locationsint 类型的数组,而不是方法要求的 ArrayList。这两个人没有太多的关系。 ArrayList 这个名字只是暗示内部使用了一个数组来保存数据。
  • 另外你可能不想对我猜的单元格使用字符串?如果它们只是数字,为什么不使用Integer
  • 裸露在外,但我将您的建议插入如下:ArrayList locations = Arrays.asList(randomNum, randomNum + 1, randomNum +2);

标签: java arraylist


【解决方案1】:

看来您必须用接受int[] loc 的新方法覆盖现有方法setLocationCells。此外,最好将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,则可以在客户端使用Streamint[] 转换为ArrayList&lt;String&gt;

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

附言 在您的示例中,您甚至不必将int[] 转换为ArrayList&lt;String&gt;,因为您可以创建ArrayList&lt;String&gt; 而不是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");
        }
    }
}

【讨论】:

  • 它说当我这样做时,我引用:“嵌套类型 DotCom 不能隐藏封闭类型”。
  • 好的!你解决了!这真的很好用。对于那些想知道为什么我的代码没有打印出结果的人,那是因为我不小心删除了“System.out.println(result);” line.谢谢你的帮助,你这个小传奇。
猜你喜欢
  • 2021-11-27
  • 1970-01-01
  • 2020-04-08
  • 2023-03-26
  • 1970-01-01
  • 2021-04-07
  • 1970-01-01
  • 2014-10-09
  • 1970-01-01
相关资源
最近更新 更多