我正在编写的程序是确定一年是否是闰年。这是一个作业,所以我需要使用我在程序中编写的四个方法。程序编译并运行,它在适当的地方要求用户输入,但它不接受输入到程序中。也就是说这一年是闰年,无论输入什么都循环。我很困惑哪里有错误,因为这个程序似乎与我们给出的例子相匹配。
import java.util.Scanner;
public class LeapYear {
public static void main(String[] args) {
boolean repeat;
String computeanother, yes="yes";
Scanner kb=new Scanner(System.in);
int year = -1;
boolean leap;
do
{
displayInstructions();
getYear(year);
leap = isLeap(year);
displayResults(year, leap);
System.out.println("Would you like to compute another year?");
computeanother = kb.nextLine();
if(computeanother.equals(yes))
repeat=true;
else
repeat=false;
} while(repeat=true);
}
public static void displayInstructions()
{
System.out.println("This program is designed to predict whether or not a year is a leap year.");
System.out.println("When prompted please enter a positive number for the year.");
System.out.println("Once the program has run completely, it will state the year and whether it is a leap year.");
}
public static void getYear(int year)
{
Scanner kb = new Scanner(System.in);
do {
System.out.println("Please enter the year.");
year=kb.nextInt();
} while (year < 0);
}
public static boolean isLeap(int year)
{
boolean leap;
if ((year%4==0 && year%100 != 0) || year%400==0){
leap = true;
return true;
} else {
leap = false;
return false;
}
}
public static void displayResults(int year, boolean leap)
{
if (leap = true) {
System.out.println("The year " +year);
System.out.println("is a leap year.");
} else {
System.out.println("The year " +year);
System.out.println("is not a leap year.");
}
}
}
感谢大家的帮助!编辑后的代码如下所示:
import java.util.Scanner;
public class LeapYear{
public static void main(String[] args){
boolean repeat;
String computeanother, yes="yes";
Scanner kb=new Scanner(System.in);
int year = -1;
boolean leap;
do
{
displayInstructions();
getYear(year);
leap = isLeap(year);
displayResults(year, leap);
System.out.println("Would you like to compute another year?");
computeanother = kb.nextLine();
repeat = computeanother.equals(yes);
}while(repeat);
}
public static void displayInstructions()
{
System.out.println("This program is designed to predict whether or not a year is a leap year.");
System.out.println("When prompted please enter a positive number for the year.");
System.out.println("Once the program has run completely, it will state the year and whether it is a leap year.");
}
public static int getYear(int year)
{
Scanner kb = new Scanner(System.in);
do{
System.out.println("Please enter the year.");
year=kb.nextInt();
}while (year < 0);
return year;
}
public static boolean isLeap(int year)
{
boolean leap;
year = getYear(year);
if ((year%4==0 && year%100 != 0) || year%400==0){
leap = true;
return true;}
else{
leap = false;
return false;}
}
public static int displayResults(int year, boolean leap)
{
year = getYear(year);
if (leap == true){
System.out.println("The year " +year);
System.out.println("is a leap year.");}
else{
System.out.println("The year " +year);
System.out.println("is not a leap year.");}
return year;
}
}