【问题标题】:if condition always returns true (Java)if 条件总是返回 true (Java)
【发布时间】:2015-03-07 18:23:11
【问题描述】:

我正在尝试实现一个不可避免地显示明天的日期、月份和年份的日期系统。

我遇到的问题是 if 语句之一总是返回 true,而后面的语句总是返回 false。

这是我的代码的一部分:

public class dateVerification {

    int tomorrowDay = 0;
    int tomorrowMonth = 0;
    int tomorrowYear = 0;
    int day = 0;
    int month = 0;
    int year = 0;

    public void date() {

        Scanner myScanner = new Scanner(System.in);
        System.out.println("Enter the day");
        day = myScanner.nextInt();
        System.out.println("Enter the month");
        month = myScanner.nextInt();
        System.out.println("Enter the year");
        year = myScanner.nextInt();

        switch (month) {
            case 1:
                if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10) {
                    if (day < 31) {
                        tomorrowDay = day + 1;
                    } else {
                        tomorrowDay = 1;
                        tomorrowMonth = month + 1;
                    }
                }
                break;

返回 true 的行是:

 if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10)

其他一切都返回错误,即我的案例 2 陈述

if (month == 4 || month == 6 || month == 9 || month == 11)

有人能解释一下吗?

【问题讨论】:

  • case 1month 上,所以 month == 1 总是正确的也就不足为奇了,对吧?
  • 你在month变量中传递了什么输入??
  • 这个语句在代码中的什么位置? if (month == 4 || month == 6 || month == 9 || month == 11)

标签: java date if-statement conditional-statements


【解决方案1】:

您正在测试month 字段。

在情况 1 中,月份始终为 1。

 switch (month) {
            case 1:  //mount = 1 !!
                if (month == 1 ||...
     //
 }

【讨论】:

  • 干杯,我理解你的推理,但如果不添加更多 if 语句,我将如何测试其他月份?
  • switch (month) { case 1: //... break; case 2: //... break; ..... case 12: //...break; }
  • 谢谢!我意识到我的错误。我不得不对 switch 语句进行一些阅读。我现在已经开始工作了。 :D
【解决方案2】:

在java中获得明天最简单的方法是

public Date nextDate(Date currentDate) {
    Calendar c = Calendar.getInstance(); 
    c.setTime(currentDate); 
    c.add(Calendar.DATE, 1);
    return c.getTime();
}

【讨论】:

    【解决方案3】:

    您代码中的问题出在这部分:

     } else {
                            tomorrowDay = 1;
                            tomorrowMonth = month + 1;
    

    既然要增加31天的月份,就应该改成

     } else {
                            tomorrowDay = 1;
                            month = month + 1;
    

    增加月份并退出循环,否则你永远不会离开它,因为月份(这是你检查的永远不会改变值)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-01-04
      • 2015-12-16
      • 2016-05-10
      • 1970-01-01
      • 2023-04-07
      • 1970-01-01
      • 2012-09-08
      • 1970-01-01
      相关资源
      最近更新 更多