【问题标题】:Java: Referring to the object before the dot operator in a methodJava:在方法中引用点运算符之前的对象
【发布时间】:2014-06-14 18:08:59
【问题描述】:

所以,这就是问题所在。我制作了一个 Time 类,它允许我创建时间对象。在我的时间课程中,我创建了一个名为minutesUntil 的方法。 minutesUntil 告诉我两次之间的分钟差。

拨打minutesUntil,我使用了这条线路。

time1.minutesUntil(time2)

这是minutesUntil中的代码。

 public int minutesUntil(Time other){
    int otherTotalMinutes = other.getMinutes() + (other.getHours() * 60);
    int thisTotalMinutes = ??.getMinutes() + (??.getHours() * 60);
    return (otherTotalMinutes - thisTotalMinutes);
}

我用什么代替第三行的问号来引用minutesUntil 方法中的time1 对象。

【问题讨论】:

标签: java methods reference dot-operator


【解决方案1】:

如果我理解正确,你想要this;那是

int thisTotalMinutes = ??.getMinutes() + (??.getHours() * 60);

应该是

int thisTotalMinutes = this.getMinutes() + (this.getHours() * 60);

也可以这样表达

// Using "this" implicitly.
int thisTotalMinutes = getMinutes() + (getHours() * 60);

【讨论】:

  • 谢谢。我以为我应该使用“这个”。 ,但是当我使用“this.”运行程序时没有得到正确的值,所以我假设我使用了“this.”。不正确。再次尝试后,它成功了。我想我犯了一些愚蠢的错误。谢谢。 :)
  • @Underdisc 在执行减法之前,您可能需要检查哪个值更大。
  • 这是我检查的第一件事,它现在完全按照预期工作。再次感谢。 :)
【解决方案2】:

那里不需要任何东西。摆脱点。改变这个:

int thisTotalMinutes = ??.getMinutes() + (??.getHours() * 60);

到这里:

int thisTotalMinutes = getMinutes() + (getHours() * 60);

如果您愿意,也可以使用this,但我认为在this 情况下没有必要用this 混淆代码。

【讨论】:

    猜你喜欢
    • 2019-01-18
    • 1970-01-01
    • 1970-01-01
    • 2018-10-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-14
    • 2016-03-28
    相关资源
    最近更新 更多