3

我正在尝试模拟手机。我创建了以下方法:

  1. 加载
  2. 称呼
  3. 发送文本消息
  4. 加载
  5. getTotalMinutesCalled
  6. 变化率
  7. 打印总结
  8. 传递加载到

我的问题是,当我将一个对象传递给该passLoadTo()方法,然后打印该对象的摘要时,它不会改变该对象的状态。

这是我正在尝试做的事情:

public class MobilePhone {

    private double credit;
    private int totalMinutes;
    private double ratePerCall;
    private int numOfText;

    MobilePhone()
    {
        credit = 0;
        totalMinutes = 0;
        ratePerCall = 6.50;
        numOfText = 0;
    }

    public void load(double pesos) {
        if(pesos > 25) {
            credit = credit + pesos;
        } else {
            //System.out.println("The attempting to use this service is forbidden.");
            //System.out.println();
        }
    }

    //other code

    public void printSummary() {
        System.out.printf("Credit left: P%.2f" ,getLoadLeft());
        System.out.println();
        System.out.println("Total call duration "+getTotalMinutesCalled()+" mins");
        System.out.printf("Rate per call: P%.2f" ,ratePerCall);
        System.out.println();
        System.out.println("Number of text message send: " +getNumTextMessage());
        System.out.println();
    }

    public void passLoadTo(MobilePhone dest, double amount) {
        if(credit > amount) {
            credit = credit - amount;
            dest.load(amount);  
        }  else {
            System.out.println("fail");
            System.out.println("The attempting to use this service is forbidden.");
            System.out.println();
        }

    }
}

此代码用于测试目的:

public class Main {
    public static void main(String[] args) {

        MobilePhone mp = new MobilePhone();
        MobilePhone mp1 = new MobilePhone();

        mp.load(30);
        mp.printSummary();
        mp.changeRate(1);
        mp.printSummary();


        mp.call(1);
        mp.printSummary();

        System.out.println(mp.getTotalMinutesCalled());

        mp.passLoadTo(mp1, 30);
        mp.printSummary();

        mp1.printSummary();
    }
}

我想要的是每当我创建一个 2 移动对象(mp 和 mp1)并调用 mp.passLoadTo(mp1,1) 方法时,mp1 摘要的摘要打印我从 mp 添加到 mp1 的负载

4

1 回答 1

2

您的主要问题是:

 if(credit > amount) {

您正在检查 credit 是否大于 amount,但您只加载 30 并花费 30,这将失败(30 > 30)

于 2013-06-28T16:53:24.783 回答