无法弄清楚如何退出我的程序循环

时间:2014-10-12 03:36:47

标签: java loops

我正在为一个闰年检查员的课程编写程序。我从我理解的循环开始工作,但它仍然进入无限循环?零不会终止程序。我曾经尝试过使用其他,如果,如果,虽然,我做错了什么?这是我第三次改写这个并且现在完全丢失了-_-。任何帮助或提示将不胜感激。

import java.util.Scanner;


public class LeapYearChecker {
public static void main(String[] args){
    System.out.println("Please enter a date to find out if the year is a leap year.");
    Scanner userInput = new Scanner(System.in);
    int year = userInput.nextInt();

    while(year == 0)
    {
        System.out.println();
    }
    if (year < 1582){
        System.out.println("Please enter a date after 1582.  The date you entered was" + year + ".");
    }if((year % 4 == 0) && (year % 100 !=0) || (year % 400 == 0)){
                System.out.println("That is a leap year");
            }else{
                System.out.println(year +" is not a leap year.");
            }
        }

}

3 个答案:

答案 0 :(得分:0)

第一个循环是无限的。你忘了阅读里面的用户输入。

答案 1 :(得分:0)

只有当用户输入0时,你的循环才会运行。一旦他们这样做,你的程序将陷入无限循环,因为你还没有改变你内在的year的值。

我假设你想继续提示用户输入数字直到他们输入0?然后我将重构您的main方法,以便它包围您检索和处理输入的代码。像这样:

System.out.println("Please enter a date to find out if the year is a leap year.");
Scanner userInput = new Scanner(System.in);
int year;

do {
    year = userInput.nextInt();

    /**
     * Print some message based input. 
     */
} while (year != 0); // Loop until user enters 0

答案 2 :(得分:0)

while (year == 0)
{
    System.out.println();
}

您的问题是,如果年份为0,您的程序将无限输出新行。

此外,检查是否为闰年的ifs不在循环体内,因此即使输入非零数字,代码也只会运行一次。

请尝试以下代码,请务必阅读评论以了解正在进行的操作:

public static void main(String[] args)
{
    Scanner in = new Scanner(System.in);
    int year = -1; //Give your int a default value so the main loop will execute
    while (year != 0) //-1 not equal to zero, so your code will start
    {
        System.out.print("Please enter a year: "); //Now we get the value of the year
        year = in.nextInt(); //Put it into our variable
        if (year < 1582) //And if it's less than 1582
        {
            if (year != 0)
                System.out.println("Year must not be less than 1582!"); //Notify the user, unless they are exiting the program
            continue; //restart the while loop, this is quite a useful statement!
        }
        if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0) //Check if it's a leap year
            System.out.println("That is a leap year!\n"); 
        else
            System.out.println("That is not a leap year :(\n");
        //End of the loop, so it goes back to the beginning, which asks the user again for the year
        //So if you enter 0 next the program will close
    }
}