【问题标题】:Java Programming Help: Trouble with If statement directionJava 编程帮助:If 语句方向的问题
【发布时间】:2012-09-18 08:42:11
【问题描述】:

我已经编写了一个测试闰年的代码,但希望添加一个修正来说明它是否在过去。为此,我添加了一个条件,即如果输入恰好是 2012 年或更大,那么现在时证明是正确的,否则它采用过去时。就目前而言,它忽略了这个限定符,只执行第一条语句。任何帮助完成这项工作将不胜感激。

代码如下

{
    int input;

    System.out.println("Enter year:");
    Scanner keyboard = new Scanner(System.in);
    input = keyboard.nextInt();

    while (input >= 2012){

    if ((input%4==0) && input%100!= 0)
    {
        System.out.println(input + " is a leap year.");
    }
    else if (input%400==0)
    {
        System.out.println(input + " is a leap year.");
    }
    else
    {
        System.out.println(input + " is not a leap year.");
      }
}
    while (input < 2012){

    if ((input%4==0) && input%100!= 0)
    {
        System.out.println(input + " was a leap year.");
    }
    else if (input%400==0)
    {
        System.out.println(input + " was a leap year.");
    }
    else
    {
        System.out.println(input + " was not a leap year.");
    }
}

}
}

【问题讨论】:

  • 你的 while 循环永远不会结束

标签: java loops if-statement while-loop


【解决方案1】:

我认为你错了-while (input &gt;= 2012)
使用if 而不是whileif (input &gt;= 2012)
还有if (input &lt;= 2012)

【讨论】:

    【解决方案2】:

    我认为您并不真正了解 while 循环的用途。这是一个循环,这意味着它会重复直到条件不满足。一个例子:

    x=10
    while(x!=0){ int dosomething = 1; x--}
    

    此循环重复 10 次。因此,只需将您的 while 更改为 if,代码就可以正常工作了。

    【讨论】:

    • 并记住你需要一种方法来退出这个循环(在这种情况下它是 x--)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多