所以我第一次编写自己的类,我唯一无法弄清楚的方法是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。
答案 0 :(得分:0)
您可以执行类似的操作,而不是声明int结果。
public int compareTo(SavingsAccount secAccount)
{
if ( balance > secAccount.getBalance() )
return 1;
else if ( balance == secAccount.getBalance() )
return 0;
else
return -1;
}
除非您需要该结果变量,否则这将起作用。当你可以这样做的时候,不需要编写变量的额外代码设置值。
答案 1 :(得分:0)
你可能只是有一个迷路的大括号。这是一个完整的工作示例:
文件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中将其作为Java程序运行,或者在您喜欢的IDE中运行它。