我在执行以下任务时遇到问题:
“编写一个程序,以月日年(8 23 2000)的形式接受任何两个日期,用空格分隔,并计算两个日期之间经过的总天数,包括开始天和结束天。记住闰年是可被 4 整除的年份,但必须能被 400 整除的百年年除外,例如 1600 或 2000(1800 不是闰年)。您可以使用任何键入的日期(或存储的日期)来测试您的程序在文件中),但它最终必须使用下面显示的数据运行。屏幕上的系统输出是可以接受的。”
到目前为止,我有这段代码,它可以编译:
import java.util.Scanner;
import java.io.*;
public class Project3
{
public static void main(String[] args) throws IOException
{
int m1, d1, y1, m2, d2, y2;
Scanner scan = new Scanner(new FileReader("dates.txt"));
for(int i = 0 ; i < 6; ++i)
{
m1 = scan.nextInt();
d1 = scan.nextInt();
y1 = scan.nextInt();
m2 = scan.nextInt();
d2 = scan.nextInt();
y2 = scan.nextInt();
System.out.println("The total number of days between the dates you entered are: " + x(m1, m2, d1, d2, y1, y2));
}
}
public static int x (int m1, int d1, int y1, int m2, int d2, int y2)
{
int total = 0;
int total1 = 0;
int total2 = 0;
if( m1 == m2 && y1 == y2)
{
total = d2 - d1 +1;
}
else if ( y1 == y2 )
{
total = daysInMonth( m2 , y2 ) - d1 + 1;
}
for(int i = m1; i < m2 ; ++i)
{
total1 += daysInMonth( m2, y2 );
}
for (int i = y1; i < y2; i++)
{
total2 += daysInYear ( y2 );
}
total += total1 + total2;
return total;
}
//Methods
public static boolean isLeap(int yr)
{
if(yr % 400 == 0)
return true;
else if (yr % 4 == 0 && yr % 100 !=0)
return true;
else return false;
}
public static int daysInMonth( int month , int year)
{
int leapMonth;
if (isLeap(year) == true)
{
leapMonth = 29;
}
else
{
leapMonth = 28;
}
switch(month)
{
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12: return 31;
case 4:
case 6:
case 9:
case 11: return 30;
case 2: return leapMonth;
}
return 28;
}
public static int daysInYear(int year)
{
if (isLeap(year))
return 366;
else
return 365;
}
}
我遇到的问题是数据文件中日期的输出不正确。我输入这两个日期7 4 1776
并1 1 1987
得到723795
而不是正确答案76882
。我输入的任何其他日期,它们也是不正确的。
这也是我得到的错误。
您输入的日期之间的总天数为:723795
线程“main”中的异常 java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:862)
at java.util.Scanner.next(Scanner. java:1485)
在 java.util.Scanner.nextInt(Scanner.java:2117)
在 java.util.Scanner.nextInt(Scanner.java:2076)
在 Project3.main(Project3.java:15)
数据文件:
7
4
1776
1
1
1987
请,非常感谢任何帮助!