gpt4 book ai didi

java - 如何将方法从A类传递到B类

转载 作者:行者123 更新时间:2023-12-01 16:02:30 26 4
gpt4 key购买 nike

有3个文件:

1. Annuuity.java
2. AnnuityDueGUI.java // GUI for Annuity Due
2. AnnuityDueResultGUI.java //GUI for the result

在 AnnuityDueGUI.java 下:

public double calculateFADGUI(){
//FVA = A{[(1+i)^n – 1] / i} (1+i)
String amountStr = amount.getText() ; //convert string to double
dAmount = Double.parseDouble(amountStr) ;
String iStr = iText.getText() ;
dInterest = Double.parseDouble(iStr) ;
String periodStr = period.getText() ;
dPeriod = Double.parseDouble(periodStr) ;
iPeriod = (int)dPeriod ;
due = new Annuity(dAmount, dInterest, iPeriod) ;
System.out.println(due.calculateFAD()) ;
return due.calculateFAD() ; //calculateFAD() is under Annuity.java
}

在 AnnuityDueResultGUI.java 下:

AnnuityDueGUI due ;

public AnnuityDueResultGUI(AnnuityDueGUI due){ //1st solution failed
this.due = due ;
}
public void grabResult(){ //1st solution failed
result = this.due.calculateFADGUI() ;
}

public AnnuityDueResultGUI(){

JPanel p6 = new JPanel() ;
p6.setLayout(new GridLayout(2, 1)) ;
p6.add(new JLabel("you will have approximately $" + result)) ;
// other codes
}

从 AnnuityDueGUI.java 我可以看到 due.calculateFAD() 的结果。但是,我想在 AnnuityDueResultGUI.java 下显示结果

我已经将它们放在名为“GUI”的包下,并且还导入了 AnnuityDueGUI.java 和 Annuity.java。

我使用未注册的用户执行了本论坛中针对我的其他相同问题建议的步骤。但是,它不起作用(通过的结果是0)。这就是为什么我再次发布相同的问题并提供更多详细信息。

请协助并提前致谢。

最佳答案

我认为您忘记调用 grabResult() 方法。

public AnnuityDueResultGUI(AnnuityDueGUI due){  
this.due = due ;
grabResult(); // calling this will store the value in the "result" instance variable

JPanel p6 = new JPanel() ;
p6.setLayout(new GridLayout(2, 1)) ;
p6.add(new JLabel("you will have approximately $" + result)) ;
// other codes
}

private void grabResult(){
result = this.due.calculateFADGUI() ;
}

顺便说一句,您应该避免在构造函数中调用非最终类的公共(public)方法。

关于java - 如何将方法从A类传递到B类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3464712/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com