【问题标题】:Required: Double, int Found: String, String必需:Double,int 找到:String,String
【发布时间】:2015-04-11 06:21:31
【问题描述】:

这是我的代码:-

公开课程序{

public static void main(String[] args) {
    if (args[0] == "interest"){
        public CompoundInerestCalculator(){
            CompoundInterestCalculator runCal = new CompoundInterestCalculator();
            if (args[1] == "annual"){
                runCal.compoundAnnually(args[2], args[3], args[4], args[5]);

            }

            else {
                args[1] = "continuous";
                runCal.continuousCompound(args[2], args[3], args[4]);
            }
        }   
    }

提取代码的下一个类:-

公共类 CompoundInterestCalculator {

// Calculation for Annual Compound Interest
public BigDecimal compoundAnnually(double principal, double rate, int periods, int years) {
    double finalAmount = principal * Math.pow( 1 + ( rate / periods), years * periods);
    double compoundInterest = finalAmount - principal;
    BigDecimal finalInterest = new BigDecimal(compoundInterest);
    System.out.print(finalInterest);
        return finalInterest;
}

// Calculation for Continuous Compound Interest
public BigDecimal continuousCompound(double principal, double rate, int years) {
    double finalAmount = principal * Math.pow( Math.E, rate * years);
    double compoundInterest = finalAmount - principal;
    BigDecimal finalInterest = new BigDecimal(compoundInterest);
    System.out.print(finalInterest);
        return finalInterest;
}

}

这是我编译程序时遇到的问题:-

必需:双精度、双精度、整数、整数

找到:字符串、字符串、字符串、字符串

原因:实参String无法通过方法调用转换为double

Program.java:19: 错误:CompoundInterestCalculator 类中的方法 ContinuousCompound 不能应用于给定类型;

【问题讨论】:

  • Java 是强类型的。您必须将这些字符串显式转换为相关类型。
  • @lared 所以你的意思是说,我必须在 runCal.compoundAnnually(args, args) 之后明确键入 args[no.] 作为所需的类型?
  • 您必须使用 Jean-Francois 在他的回答中提到的方法 - Double.parseDouble
  • @lared 好的,明白了:)

标签: java string int double


【解决方案1】:

首先,比较 String 和 .equals 而不是 ==,因为您在使用 == 比较对象时比较内存地址。

所以(args[0] == "interest")变成(args[0].equals("interest"))

其次,您将 Strings 传递给声明为

的方法
compoundAnnually(double principal, double rate, int periods, int years)

有了这个电话

runCal.compoundAnnually(args[2], args[3], args[4], args[5]);

您需要将它们解析为正确的类型...

runCal.compoundAnnually(Double.parseDouble(args[2]), Double.parseDouble(args[3]), Integer.parseInt(args[4]), Integer.parseInt(args[5]))

第三,同样适用于通话runCal.continuousCompound(args[2], args[3], args[4]);

【讨论】:

  • 嗯,错误确实消失了,但弹出了一些其他错误:D 感谢您的帮助:)
猜你喜欢
  • 2017-05-03
  • 2019-01-31
  • 1970-01-01
  • 2014-08-15
  • 1970-01-01
  • 1970-01-01
  • 2020-04-05
  • 1970-01-01
  • 2020-05-06
相关资源
最近更新 更多