我已经尝试了一些与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");
}
}
答案 0 :(得分:1)
在输入行上方使用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");
}
}
}
答案 1 :(得分:0)
你应该把输入代码放在while循环中,然后循环,直到循环,直到0或更小。
None
答案 2 :(得分:0)
你需要做一些事情让你的输入循环继续运行,直到遇到停止条件(在你的情况下是用户输入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