gpt4 book ai didi

java - For 循环未在方法中启动

转载 作者:行者123 更新时间:2023-12-01 19:31:27 26 4
gpt4 key购买 nike

我对编码非常陌生,所以我正在练习一些简单的东西,遇到了一个我已经尝试解决大约 2 个小时的问题,但我不知道它出了什么问题。

问题是,当我调用 crate.fillCrate();crate.emptyCrate(); 时,控制台中不会出现任何内容,而当我调用 crate.crateInfo(); 控制台中出现以下内容:

一箱漂亮的喜力啤酒
它包含 24 个插槽
插槽:已满。
插槽:为空。

我想这意味着我的 for 循环没有启动,但我不知道为什么......

我的主课:

public class Main {

public static void main(String[] args) {
Crate crate = new Crate(24, "Heineken");
}
}

我的 crate 类:

public class Crate {
private int crateSize;
private Bottle[] bottles = new Bottle[crateSize];
public String brand = null;

public Crate(int crateSize, String brand) {
this.crateSize = crateSize;
this.brand = brand;
}

public void fillCrate(){
for(int i = 0; i < bottles.length; i++) {
if(bottles[i] == null && !bottles[i].getSpotInfo()) {
bottles[i] = new Bottle(true);
System.out.println("Spot " + (i+1) + " is filled.");
} else {
System.out.println("Spot " + (i+1) + " was already full");
}
}
}

public void emptyCrate() {
for(int i = 0; i < bottles.length; i++) {
if(bottles[i] != null && bottles[i].getSpotInfo()) {
bottles[i].makeSpotEmpty();
System.out.println("Spot " + (i+1) + " is empty.");
} else {
System.out.println("Spot " + (i+1) + " was already empty");
}
}
}

public void crateInfo() {
System.out.println("A nice crate of " + brand);
System.out.println("It contains " + crateSize + " slots");
System.out.print("slots: ");
for(int i = 0; i < bottles.length; i++) {
if(bottles[i] != null && bottles[i].getSpotInfo()) {
System.out.print((i+1));
}
}
System.out.println(" are filled.");
System.out.print("slots: ");
for(int c = 0; c < bottles.length; c++) {
if(bottles[c] != null && !bottles[c].getSpotInfo()) {
System.out.print((c+1));
}
}
System.out.println(" are empty.");
}
}

还有我的 Bottle 类:

public class Bottle {
private boolean occupiesSpot = false;

public Bottle(boolean occupiesSpot) {
this.occupiesSpot = occupiesSpot;
}

public void makeSpotEmpty() {
occupiesSpot = false;
}

public boolean getSpotInfo() {
return occupiesSpot;
}
}

最佳答案

    private int crateSize;
private Bottle[] bottles = new Bottle[crateSize];

瓶子的大小为 0,因为 crateSize 尚未初始化,您应该这样做

    public Crate(int crateSize, String brand) {
this.crateSize = crateSize;
this.brand = brand;
this.bottles = new Bottle[crateSize];
}

还有

if (bottles[i] == null && bottles[i].getSpotInfo())

如果瓶子为空,则此行将导致 NullPointerException,因为您无法对空对象调用方法 (getSpotInfo)。也感谢@Turing85 指出了这一点。

关于java - For 循环未在方法中启动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59698706/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com