[英]How would I use a while loop to keep requesting user input
我用while循环尝试了几件事,但似乎无法使其正常工作。 我想一直请求用户输入,直到用户输入数字0,这是我到目前为止的代码:
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循环作为:
while(true)
并且,使用if
条件break
。
if(year == 0)
break;
另外, leap year
条件在您的代码中是错误的。 它应该是:
if((year % 100 == 0 && year % 400 == 0) || (year % 4 == 0 && year % 100 != 0))
//its a leap year
else
//its not
PS:在评论中,我将提供完整的代码:
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循环和执行while循环中,直到year等于或小于0。
public static void main(String[] args) {
int year = 1;
while(year > 0)
{
System.out.println("Enter a year to check if it is a leap year");
Scanner input = new Scanner(System.in);
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");
}
}
您需要做一些事情来保持输入循环运行,直到遇到停止条件为止(在您的情况下,这是用户输入0
)
// First get the scanner object with the input stream
Scanner sc = new Scanner(System.in);
// Just using do-while here for no reason, you can use a simple while(true) as well
do{
int input = sc.nextInt(); // read the next input
if (int == 0) { // check if we need to exit out
// break only if 0 is entered, this means we don't want to run the loop anymore
break;
} else {
// otherwise, do something with the input
}
} while(true); // and keep repeating
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.