我将如何使用while循环来不断请求用户输入 [英] How would I use a while loop to keep requesting user input
本文介绍了我将如何使用while循环来不断请求用户输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我用while循环尝试了几件事,但似乎无法正常工作.我想一直请求用户输入,直到用户输入数字0,这是我到目前为止的代码:
I've tried a couple of things with the while loop and can't seem to get it to work. I want to keep requesting user input until the user inputs the number 0, here is the code I have so far:
import java.util.*;
public class Task10 {
public static void main(String[] args) {
System.out.println("Enter a year to check if it is a leap year");
Scanner input = new Scanner(System.in);
int year = input.nextInt();
if ((year % 4 == 0) || ((year % 400 == 0) && (year % 100 != 0)))
System.out.println(year + " is a leap year");
else
System.out.println(year + " is not a leap year");
}
}
推荐答案
在输入行上方使用while循环作为
Use a while loop above input line as:
while(true)
然后,将if
条件用于break
.
if(year == 0)
break;
此外,leap year
的条件在您的代码中是错误的.应该是:
Also, condition for leap year
is wrong in your code. It should be:
if((year % 100 == 0 && year % 400 == 0) || (year % 4 == 0 && year % 100 != 0))
//its a leap year
else
//its not
PS:就像在评论中一样,我将提供完整的代码:
PS: As in comments, I'll give a complete code:
import java.util.*;
public class Task10 {
public static void main(String[] args) {
System.out.println("Enter a year to check if it is a leap year");
while(true){
Scanner input = new Scanner(System.in);
int year = input.nextInt();
if(year == 0)
break;
if((year % 100 == 0 && year % 400 == 0) || (year % 4 == 0 && year % 100 != 0))
System.out.println(year + " is a leap year");
else
System.out.println(year + " is not a leap year");
}
}
}
这篇关于我将如何使用while循环来不断请求用户输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文