英文:
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 <Cannon> Cannons = new LinkedList <Cannon>();
for (int i=0; i <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 < randomizer.nextInt(99) + 1; i++) {
Cannon cannon = new Cannon(randomizer.nextBoolean());
Cannons.add(cannon);
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论