对于我的java课程简介,我在这个作业问题上遇到了很多麻烦。
"设计并实施CupDispenser类。每个CupDispenser对象都有一个位置,并跟踪它当前包含的杯子数量。定义两个构造函数,为每个数据字段设置和获取方法,以及方法toString。另外,定义一个方法getOneCup,它简单地减少分配器中的杯数1.通过创建几个CupDispenser对象来演示您的类。另外,写一个驱动程序来测试你的CupDispenser课程。"
我有点将杯子递减1,但就构造者和toStrings而言,我完全失去了。任何帮助将非常感激。
public class CupDispenser {
private int nOfCups, initNum;
public CupDispenser(int num) {
this.nOfCups = num;
this.initNum = num;
}
public int decCups () {
this.nOfCups = this.nOfCups -1;
return this.nOfCups;
}
public int getNumOfCup () {
return this.initNum;
}
public static void main (String [] args) {
CupDispenser decr = new CupDispenser(10);
for (int i=0; i<decr.getNumOfCup(); i++) {
System.out.println(decr.decCups());
}
}
}
答案 0 :(得分:0)
以下是两个类,一个是CupDispenser类,我们定义我们的字段,方法,构造函数等,另一个是实例化多个具有不同属性的CupDispenser对象。
package q23463540;
public class CupDispenser {
private int numberOfCups;
private String locationOfCups;
public CupDispenser(int numberOfCups, String locationOfCups){
this.setNumberOfCups(numberOfCups);
this.setLocationOfCups(locationOfCups);
}
public int getNumberOfCups() {
return numberOfCups;
}
public void setNumberOfCups(int numberOfCups) {
this.numberOfCups = numberOfCups;
}
public String getLocationOfCups() {
return locationOfCups;
}
public void setLocationOfCups(String locationOfCups) {
this.locationOfCups = locationOfCups;
}
public void decrementCups(){
numberOfCups--;
}
@Override
public String toString() {
// TODO Auto-generated method stub
String result = ("Number of Cups = " + numberOfCups + ". Location of Cups = " + locationOfCups + ".");
return result.toString();
}
}
package org.apothem.stackoverflow;
import q23463540.CupDispenser;
public class StackOverflow {
public static void main(String[] args) {
// TODO Auto-generated method stub
CupDispenser cd1 = new CupDispenser(5, "Los Angeles");
CupDispenser cd2 = new CupDispenser(10, "New York");
System.out.println(cd1.toString());
System.out.println(cd2.toString());
cd1.setNumberOfCups(7);
cd1.setLocationOfCups("Toronto");
cd2.decrementCups();
cd2.decrementCups();
System.out.println(cd1.toString());
System.out.println(cd2.toString());
}
}