我有3个类(打印机,PaperTray和机器)和我的主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);
}
}
从我的打印机课程:
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()”时,页面的值为-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;
}
}
感谢任何帮助。
答案 0 :(得分:2)
isEmpty()
中的PaperTray
方法错误,如果true
(当它已满),它现在返回pages > 0
,如果false
则返回pages <= 0
1}}(当它为空时)。
您需要将条件切换为pages == 0
或绝对确定pages <= 0
。
答案 1 :(得分:1)
您的isEmpty()
定义似乎错了
public boolean isEmpty()
{
return pages > 0; //shouldn't it be pages <=0 ?
}