繁体   English   中英

将对象传递给单独类中的方法时遇到麻烦

[英]Trouble passing an object to method in a separate class

因此,我是第一次编写自己的类,而我一直无法弄清的唯一方法是compareTo方法,该方法应该具有“一个参数:SavingsAccount对象。将其命名为所需的名称”。

public int compareTo(SavingsAccount secAccount)
{
    int result;
    if ( balance > secAccount.getBalance() )
        result = 1;
    else if ( balance == secAccount.getBalance() )
        result = 0;
    else
        result = -1;

    return result;
}

当我尝试编译时,出现此错误:
错误:缺少return语句}

在客户端(由我的教授写的,我不应该编辑)中,这是调用compareTo方法的行:

if ( savings1.compareTo(savings2) > 0 )
        System.out.println("[client] Savings1 has the larger balance");
    else if (savings1.compareTo(savings2) == 0 )
        System.out.println("[client] Savings1 and Savings2 "
        + "have the same balance");
    else
        System.out.println("[client] Savings2 has the larger balance");

据我了解,将参数Savings2传递给compareTo,然后在我的SavingsAccount类中,该参数是secAccount作为对象SavingsAccount。

无需声明int结果,您可以执行以下操作。

public int compareTo(SavingsAccount secAccount)
{
    if ( balance > secAccount.getBalance() )
        return 1;
    else if ( balance == secAccount.getBalance() )
        return 0;
    else
        return -1;
}

除非您需要该结果变量,否则它将起作用。 只要您可以这样做,就无需编写额外的变量代码设置值。

您可能只是流浪的花括号。 这是一个完整的工作示例:

文件Test.java的内容:

package com.jlb;

public class Test{

    public static void main(String[] args)
    {
        SavingsAccount savings1 = new SavingsAccount(200);
        SavingsAccount savings2 = new SavingsAccount(100);

        if ( savings1.compareTo(savings2) > 0 )
            System.out.println("[client] Savings1 has the larger balance");
        else if (savings1.compareTo(savings2) == 0 )
            System.out.println("[client] Savings1 and Savings2 "
            + "have the same balance");
        else
            System.out.println("[client] Savings2 has the larger balance");
    }


}

文件SavingsAccount.java的内容:

package com.jlb;

public class SavingsAccount {

    private int balance = 0;

    public SavingsAccount(int amount){
        this.balance = amount;
    }
    public int getBalance(){
        return this.balance;
    }

    public int compareTo(SavingsAccount secAccount)
    {
        int result;
        if ( balance > secAccount.getBalance() )
            result = 1;
        else if ( balance == secAccount.getBalance() )
            result = 0;
        else
            result = -1;

        return result;
    }
}

您可以通过在创建Savings1和Savings2时更改值来进行测试,然后在Eclipse或您喜欢的任何IDE中将其作为Java程序运行。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM