【问题标题】:Java while loop stopping before all conditions are metJava while循环在满足所有条件之前停止
【发布时间】:2018-09-21 02:19:35
【问题描述】:

我有一个项目,我的方法获取两个日期,并且它不断向该方法添加一天,直到两个日期相等,然后您可以通过查看一天添加了多少次来查看日期相距多远。我的问题是,当满足日期条件时,我的 while 循环将退出,即使日期、月份和年份都必须相同才能停止工作

    while (pastDate.getDay() != futureDate.getDay() && 
    pastDate.getMonth() != futureDate.getMonth()  && 
    pastDate.getYear() != futureDate.getYear()){

【问题讨论】:

    标签: java


    【解决方案1】:

    您需要将ORwhile 循环中的条件组合在一起:

    while (pastDate.getDay() != futureDate.getDay() ||
           pastDate.getMonth() != futureDate.getMonth()  ||
           pastDate.getYear() != futureDate.getYear()) {
        // do something
    }
    

    在伪代码中,当两个日期相等时循环的逻辑是:

    while (day1 == day2 && month1 == month2 && year1 == year2) {
        // ...
    }
    

    根据德摩根定律,P AND Q 的对立面是~P OR ~Q,当日期 相等时,它将导致以下while 循环(再次以伪代码形式):

    while (day1 != day2 || month1 != month2 || year1 != year2) {
        // ...
    }
    

    【讨论】:

    • 不应该将day1 = day2 替换为伪代码中的相等检查吗?
    【解决方案2】:

    使用.equals():

    while (!pastDate.equals(futureDate)) {
        //
    }
    

    它不仅更具可读性,而且准确地如何将日期视为等同于实现,这正是 OOP 最佳实践所说的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-01-29
      • 2013-11-22
      • 1970-01-01
      • 1970-01-01
      • 2016-03-14
      • 1970-01-01
      • 1970-01-01
      • 2019-05-16
      相关资源
      最近更新 更多