写Java程序,包含Telephone,Telephone类中包含电话品牌、电话号码、通话时间、费率、余额等属性,以及计算话费和现实信息等方法。
需要给充值的方法带一个形式参数,其他方法不需要形式参数。另外,三个成员方法都是对属性的改变和输出各个属性的值,因此不需要返回值。编写如下:
public class Telephone {
String brand;
String number;
double dialledTime;
double rate;
double balance;
public Telephone(String brand, String number, double balance) {
this.brand = brand;
this.number = number;
this.balance = balance;
}
public void rechange(double cost) {
balance = balance+cost;
System.out.println("充值后的余额为:" +cost);
}
public void callCost() {
double callCost = dialledTime*rate;
balance=balance-callCost;
System.out.println("话费为:" +callCost);
System.out.println("余额为:" +balance);
}
public void display() {
System.out.println("电话品牌:" +brand+ ", 电话号码:" +number+ ", 通话时间:" +dialledTime+ ", 费率:" +rate);
}
}
编写测试类,创建一个对象。假设品牌是“菠萝手机”,号码是”123456“,初始余额为200元,计算通话时间为250分钟,每分钟费率是0.3。并计算充值300元后的电话余额。代码如下:
public class TelephoneTest {
public static void main(String[] args) {
// TODO Auto-generated method stub
Telephone test;
test = new Telephone("菠萝牌","123456",200);
test.dialledTime = 250;
test.rate = 0.3;
test.rechange(300);
test.callCost();
test.display();
}
}
运行结果为: