Java 如何让它在不转换为字符串的情况下返回double

Java 如何让它在不转换为字符串的情况下返回double,java,string,return,double,Java,String,Return,Double,我收到的错误是最后一行。它说:“类型不匹配:无法从字符串转换为双精度” 它要求我改成公共字符串 谢谢 在方法签名中,将方法的返回类型声明为double 但是,这一行: public double futureInvestmentValue(int years) { DecimalFormat dfWithTwoDecimalPlaces; dfWithTwoDecimalPlaces = new DecimalFormat("0.00"); double futureIn

我收到的错误是最后一行。它说:“类型不匹配:无法从字符串转换为双精度” 它要求我改成公共字符串


谢谢

在方法签名中,将方法的返回类型声明为double

但是,这一行:

public double futureInvestmentValue(int years) {
    DecimalFormat dfWithTwoDecimalPlaces;
    dfWithTwoDecimalPlaces = new DecimalFormat("0.00");
    double futureInvestmentValue = deposit * Math.pow((1 + (AnnualInterestRate / 12)), years * 12);
    return dfWithTwoDecimalPlaces.format(futureInvestmentValue);

调用返回字符串的方法。您必须决定此函数的实用性,以及是否需要它来返回预格式化的值或将此责任留给调用方。

如何以十进制格式返回双精度值。似乎每次我尝试使用dfWithTwoDecimalPlaces.format()时,都会出现错误。double数据类型并不像您想象的那样以十进制格式表示。DecimalFormat format方法是一种实用方法,用于获取实例化时指定的双精度值的打印格式表示形式。简单的回答是,你不能返回十进制格式的双精度。那么,这是我在main()中更改的东西吗?将双精度格式更改为十进制格式?@Jack Pavlov:不!你没有“改变”任何东西。一个double就是一个double,一个string就是一个string(正如Spencer Brett正确地告诉您的那样),您的方法需要传递其中一个。最佳方法:1)保持“double”为
futureInvestmentValue()
返回值(您想要返回一个“数字”!),2)无论何时您真正想要打印值(例如,到控制台或GUI),都使用Java(与上面的方法类似)。我如何以double格式(0.00)而不是“1383.422759428736”返回值这是我应该在main()中执行的操作吗?“Double”没有“格式”。它只是一个数字,一个抽象的“值”。“印刷”——你如何表现价值——与价值本身无关。在任何需要的地方使用“格式”语句。寻找或寻找两个完全不同的选择。另请参见Javadoc:
return dfWithTwoDecimalPlaces.format(futureInvestmentValue);
public double futureInvestmentValue(int years) {
    // DecimalFormat dfWithTwoDecimalPlaces; // Don't need this
    // dfWithTwoDecimalPlaces = new DecimalFormat("0.00"); // Don't need this, either
    double futureInvestmentValue = deposit * Math.pow((1 + (AnnualInterestRate / 12)), years * 12); // This is *ALL* you need!
    //return dfWithTwoDecimalPlaces.format(futureInvestmentValue); // Nope: don't return a string!
    return futureInvestmentValue; // return the double!