我必须写一个PhonePlan对象,它代表客户对他/她手机的计划类型。因此,对象必须跟踪minutesAllowed(int),minutes used(int),dataAllowed(int),data used(int)和planType(boolean):
public class PhonePlan {
int minutesAllowed;
int minutesUsed;
int dataAllowed;
int dataUsed;
boolean planType;
}
我需要编写一个构造函数,其中包含minutesAllowed,dataAllowed和planType作为参数:
public PhonePlan (int ma, int da, boolean pt){
this.minutesAllowed = ma;
this.planType = pt;
this.dataAllowed = da;
}
最后,我必须编写一个字符串方法,根据计划的类型显示计划。
我还必须使用以下测试程序测试我的代码;
public class PlanTestProgram {
public static void main(String args[]) {
System.out.println(new PhonePlan(200, 2500000, false));
System.out.println(new PhonePlan(250, 500000, true));
System.out.println(new PhonePlan(300, 5000000, false));
System.out.println(new PhonePlan(60, 1000000, false));
System.out.println(new PhonePlan(30, 0, true));
}
第一个元素是minutesAllowed,第二个元素是dataAllowed的数量,第三个元素是说明planType是否为false。
我尝试了很多不同的东西,但是我无法构造一个toString()方法,如果我的planType是真或假,则考虑到它...
我的尝试:
public String toString(){
return ( "Regular(" + minutesAllowed + " minute," + dataAllowed
+ "GB data) Monthly Plan with "
+ getMinutesRemaining() + " minutes remaining and "
+ getDataRemaining() + "KB remaining");
}
答案 0 :(得分:0)
您可以按照以下代码
中的描述实现toString方法public class PhonePlan {
int minutesAllowed;
int minutesUsed;
int dataAllowed;
int dataUsed;
boolean planType;
public PhonePlan (int ma, int da, boolean pt){
this.minutesAllowed = ma;
this.planType = pt;
this.dataAllowed = da;
}
@Override
public String toString() {
return planType ? getPlanTypeBasedString("Weekly Plan") : getPlanTypeBasedString("Monthly Plan");
}
public String getPlanTypeBasedString(String planType){
return ( "Regular(" + minutesAllowed + " minute," + dataAllowed
+ "GB data) "+planType+" with "
+ getMinutesRemaining() + " minutes remaining and "
+ getDataRemaining() + "KB remaining");
}
答案 1 :(得分:0)
您可以使用简写if / else 轻松更新建议(尝试)return
方法中的toString
,如下所示:
return ("Regular(" + minutesAllowed + " minute," + dataAllowed
+ "GB data) " + ((PlanType)? "Monthly": "Annual") + " Plan with "
+ getMinutesRemaining() + " minutes remaining and "
+ getDataRemaining() + "KB remaining");
答案 2 :(得分:0)
Metod toString()
来展示对象属性的值。对于覆盖,您可以使用公共库
public String toString() {
return new ToStringBuilder(this).
append("minutesAllowed", minutesAllowed).
append("minutesUsed", minutesUsed).
append("dataAllowed", dataAllowed).
append("dataUsed", dataUsed).
append("planType", planType).
toString();
}