在Java中向链表中添加布尔值。

huangapple go评论73阅读模式
英文:

Adding boolen to LinkedList in Java

问题

我应该创建一个 `Cannon` 对象的列表限制使用 `for` 循环),并加载所有未加载的 `Cannon`。

我的问题在于这里

```java
public static void main (String[] args) throws java.lang.Exception{
    Random randomizer = new Random();
    Cannon cannon = new Cannon (randomizer.nextBoolean());
    List<Cannon> Cannons = new LinkedList<Cannon>();
    for (int i=0; i < randomizer.nextInt(99)+1; i++){
        cannon = randomizer.nextBoolean();
        Cannons.add(cannon);
    }
}

该程序报错为 不兼容的类型:无法将 boolean 转换为 Cannon,第33行

如果您想查看完整的代码,这是链接:
https://kodilla.com/pl/project-java/175236


<details>
<summary>英文:</summary>

I am supposed to create list of `Cannon` objects (restricted to use `for-loop`) and load every `Cannon` that is not loaded.

My problem lies here:

``` java
public static void main (String[] args) throws java.lang.Exception{
    Random randomizer = new Random();
    Cannon cannon = new Cannon (randomizer.nextBoolean());
    List &lt;Cannon&gt; Cannons = new LinkedList &lt;Cannon&gt;();
    for (int i=0; i &lt;randomizer.nextInt(99)+1; i++){
    cannon = randomizer.nextBoolean();
    Cannons.add(cannon);
}

the program results with error incompatible types: boolean cannot be converted to Cannon, line 33

If you want to see the whole Code here is the link:
https://kodilla.com/pl/project-java/175236

答案1

得分: 1

你正在创建一个类型为Cannon的实例,然后试图重新将其分配给另一个类型(在这种情况下为布尔类型)。

Java是静态类型的。你不能这样随意地将一个类型重新分配给另一个类型。

如果你需要用变量填充一个列表,只需按照以下方式进行操作:

// 删除这里的方法
Cannon cannon = new Cannon(randomizer.nextBoolean());

// 并将其放入for循环中
for (int i = 0; i < randomizer.nextInt(99) + 1; i++) {
    Cannon cannon = new Cannon(randomizer.nextBoolean());
    Cannons.add(cannon);
}
英文:

You are creating one instance of type Cannon and then trying to re-assign it no another type (in this case a boolean).

Java is statically typed. You cannot re-assign one type to another type just like that.

If you need to populate a list with variables, then just do the following

// Remove this method here
Cannon cannon = new Cannon (randomizer.nextBoolean());

// and place it in the for-loop
for (int i = 0; i &lt; randomizer.nextInt(99) + 1; i++) {
    Cannon cannon = new Cannon(randomizer.nextBoolean());
    Cannons.add(cannon);
}

huangapple
  • 本文由 发表于 2020年10月9日 01:20:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/64267623.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定