这是驱动程序代码。
package javaPackage;
public class Driver{
public static void main(String args[]){
MobilePhone mp = new MobilePhone();
mp.load(34.50);
mp.call(3);
mp.sendTextMessages();
mp.printSummary();
System.out.println(mp.getNumTextMessages());
System.out.print("Total minutes called: "+mp.totalMinutesCalled);
}
}
这是mobilePhone类。
package javaPackage;
public class MobilePhone {
double creditsLeft;
int totalMinutesCalled;
double ratePerCall;
int textMessagesSent;
public MobilePhone(){
creditsLeft=0;
totalMinutesCalled=0;
ratePerCall=6.50;
textMessagesSent=0;
}
public void call(int minutes) {
totalMinutesCalled=minutes;
}
public int getTotalMinutesCalled(){
return totalMinutesCalled;
}
public void load( double pesos ) {
creditsLeft=pesos-(ratePerCall*totalMinutesCalled);
}
public void changeRate(double newCallRate) {
ratePerCall=newCallRate;
}
public void sendTextMessages(){
if(creditsLeft>0){
textMessagesSent++;
creditsLeft--;
}
else
{
System.out.println("Not enough balance");
}
}
public int getNumTextMessages()
{
return textMessagesSent ;
}
public void printSummary() {
System.out.println("Credits left:"+ (creditsLeft));
System.out.println("Total call duration:" +totalMinutesCalled);
System.out.println("Rate per call:"+ ratePerCall);
System.out.print("Numer of text messages sent:" );
}
}
我已将totalMinutesCalled
设置为3
,但当我在方法totalMinutesCalled
中使用load()
来计算余额时,totalMinutesCalled
变为{{1}所以我无法得到所需的结果。当我在0
方法之外显示totalMinutesCalled时,奇怪的是,它显示了正确的值。那是为什么?
输出
load()
提前致谢!
答案 0 :(得分:3)
您在 call
之后调用load
方法,因此最初变量totalMinutesCalled
的值为0
。
答案 1 :(得分:2)
int totalMinutesCalled;
的默认值为0
。
因此,当您致电mp.load(34.50);
时,totalMinutesCalled
的值为0
。首先call()
然后load()
如下所示:。
mp.call(3);
mp.load(34.50);