gpt4 book ai didi

Java 教程 .isEmpty() 方法

转载 作者:行者123 更新时间:2023-12-01 23:15:27 25 4
gpt4 key购买 nike

我有 3 个类(Printer、PaperTray 和 Machine)和我的主 Java 类(HelloWorld)。

我期待看到“装入更多纸张!”作为调用“myPrinter.print(2)”时的输出,但输出显示“我的打印机已打开!”两次,就好像托盘中有纸一样。如果有足够的纸张被传递到 loadPaper 中,我应该只会看到显示打印机两次的输出(暂时已被注释掉,直到我使加载纸张正常工作):

import printing.Printer;

public class HelloWorld {

public static void main(String[] args)
{
Printer myPrinter = new Printer(true, "MY PRINTER");
//myPrinter.loadPaper(3);
myPrinter.print(2);
}
}

来 self 的打印机类:

package printing;

public class Printer extends Machine
{
private String modelNumber;
private PaperTray paperTray = new PaperTray(); //printer now HAS paper tray

public Printer(boolean isOn, String modelNumber)
{
super(isOn); //calls the constructor of the machine class - Super calls inherited parent
this.modelNumber = modelNumber;
}

public void print(int copies)
{
String onStatus = "";
if(isOn)
{
onStatus = " is On!";
}
else
{
onStatus = " is Off!";
}

String textToPrint = modelNumber + onStatus;

while(copies > 0 && !paperTray.isEmpty())
{
System.out.println(textToPrint);
copies--;
paperTray.usePage();
}

if(paperTray.isEmpty())
{
System.out.println("Load more paper!");
}
}

//for each
public void printColours()
{
String[] colours = new String[] {"Red", "Blue", "Green", "Yellow" };

//for current colour "in" colours
for(String currentColour : colours)
{
if("Green".equals(currentColour))
{
continue;
}
System.out.println(currentColour);
}
}

public void print(String text)
{
System.out.println(text);
}

public String getModelNumber()
{
return modelNumber;
}

public void loadPaper(int count)
{
paperTray.addPaper(count);
}

}

当调用“.isEmpty()”时,pages的值为-2,但我相信“.isEmpty()”仅在该值等于0时才有效?所以这就是我猜测我的问题所在。然而我的代码(99%确定)与导师的示例相同。

PaperTray 类是:

public class PaperTray {

int pages = 0;

public void addPaper(int count)
{
pages += count;
}

public void usePage()
{
pages--;
}

public boolean isEmpty()
{
return pages > 0;
}
}

机器类别:

public class Machine {

protected boolean isOn;

public Machine(boolean isOn)
{
this.isOn = isOn;
}

public void TurnOn()
{
isOn = true;
}

public void TurnOff()
{
isOn = false;
}

}

感谢任何帮助。

最佳答案

您的isEmpty() PaperTray中的方法是错误的,现在返回 true如果pages > 0 (当它已满时),并返回 false如果pages <= 0 (当它为空时)。

您需要将条件切换为pages == 0或者绝对确定pages <= 0 .

关于Java 教程 .isEmpty() 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21289019/

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