简体   繁体   English

让我的程序回到“顶部”(如果声明)(Java)

[英]Getting my program to go back to the “top” (if statement) (Java)

I have a program to calculate leap year, however, it only works past about the year 1750 so I want my user to only be able to input numbers past 1750. 我有一个计算leap年的程序,但是它只能在1750年左右才能使用,因此我希望我的用户只能输入1750年以后的数字。

System.out.println("Enter a year after 1750:");
    leapYear = in.nextInt();

    if(leapYear<1750){
        System.out.println("You have entered a year before 1750, please try again :");
        leapYear  = in.nextInt();
    }

My solution was to put a if statement. 我的解决方案是放置一个if语句。 I realize, however, that this will only work if the user inputs something below 1750 once. 但是,我意识到,只有在用户输入低于1750的值时,这才起作用。 if they do it again the program will move on. 如果他们再次这样做,程序将继续运行。 Is there a way I can execute the statement "You have entered a year before 1750, please try again :" as many times as I need to without re writing it?. 有没有一种方法可以执行我多次需要执行的语句“您已输入1750年之前的年份,请再试一次:”,而无需重写它。

I was thinking maybe a while statement could work (if a while statement works how could I do it without causing an infinite loop)? 我在想也许一个while语句可以工作(如果一个while语句可以工作,我怎么做而不引起无限循环)?

You're on the right track with a while statement. 使用while语句可以使您处在正确的轨道上。 It's pretty simple to keep it from executing infinitely. 使其无限执行非常简单。 As soon as the user enters a correct year, the loop condition will evaluate to false and exit. 用户输入正确的年份后,循环条件将评估为false并退出。

System.out.println("Enter a year after 1750:");
leapYear = in.nextInt();

while(leapYear < 1750){
     System.out.println("You have entered a year before 1750, please try again :");
     leapYear  = in.nextInt();
}

You could also try a do-while loop to cut down on repeated code: 您还可以尝试do-while循环以减少重复的代码:

do{
    System.out.println("Please enter a year after 1750:");
    leapYear = in.nextInt();
}while(leapYear < 1750);

The user will just be reprompted to enter a year after 1750, which takes care of needing an error message. 仅会提示用户输入1750年之后的年份,这需要输入错误消息。

while(leapYear<1750)

代替:

if(leapYear<1750)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM