我有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;
}
}
任何帮助都是非常感谢的。
发布于 2014-01-22 08:55:20
isEmpty()
方法在PaperTray
中是错误的,它现在返回true
if pages > 0
(当它已满时),并返回false
if pages <= 0
(当它是空的)。
您需要将条件切换为pages == 0
或绝对确定为pages <= 0
。
发布于 2014-01-22 08:55:02
您的isEmpty()
定义似乎是错误的
public boolean isEmpty()
{
return pages > 0; //shouldn't it be pages <=0 ?
}
https://stackoverflow.com/questions/21289019
复制相似问题