超出范围的静态方法

问题描述 投票:0回答:1

因此,在我参加的 CodeHS 课程中,我试图将美分与银行账户余额分开。 Ex 将 12.34 转到 34。我尝试使用 value.indexOf() 和 value.length() 来评估余额。但是,我不断收到“您可能忘记声明 length() 或者它超出范围”错误。我很困惑,因为我认为这些是内置于 Java 本身的,但也许不是?我已经浏览了文档,但我仍然迷失方向。如有任何帮助,我们将不胜感激。

这是该方法的代码(我认为这是一个 idk 词汇 lmao 的方法)

public class Currency
{
    private Double value;
    
    // Constructor
    public Currency(Double startValue)
    {
        value = startValue;
    }
    
    // Sets value to newValue
    public void setValue(Double newValue)
    {
        value = newValue;
    }
    
    // Returns the dollar portion of value
    // if value is 12.34, returns 12
    public Integer getDollars()
    {
        return (int)value.doubleValue();
    }
    
    // Returns the cents portion of value
    // as an Integer
    // if value is 12.34, returns 34
    public Integer getCents()
    {
        return value.subSequence(value.indexOf("."), value.length());
    }
    
    // Returns a String representation
    // in the format
    // $12.34
    public String toString()
    {
        return value.doubleValue();
    }
}
java methods
1个回答
0
投票

正如 Jon Skeet 所评论的那样,您将 Double

 视为文本。这不是文字。

如果您想要文本,请创建一个

String

 对象。致电
Double#toString

String s = my double.toString() ;

String

 提供您寻求的 
indexOf
length
 方法。

© www.soinside.com 2019 - 2024. All rights reserved.