我一直在从我的程序中得到错误的数字

时间:2018-01-30 18:08:20

标签: java loops

我正在尝试编写一个程序,其中用户输入2个日期,程序计算两者之间的天数(不使用任何日历类)并打印结果,但我不断发现没有意义的疯狂数字。当我试图计算5天时,它打印出333的结果,当我尝试做20年的事情时,它会打印出数百万的数字。

import java.util.Scanner;

public class DaysCalc {

public static void main(String[] args){
    Scanner input = new Scanner(System.in);



System.out.print("Please enter starting date (mm-dd-yyyy) ");
String startingdate = input.next();

System.out.print("Please enter ending date (mm-dd-yyyy) ");
String finishingdate = input.next();

String startingdayst = startingdate.substring(3, 5);

String startingmonthst = startingdate.substring(0, 2);

String startingyearst = startingdate.substring(6, 10);

String finishingdayst = finishingdate.substring(3, 5);

String finishingmonthst = finishingdate.substring(0, 2);

String finishingyearst = finishingdate.substring(6, 10);

int startingyear = Integer.parseInt(startingyearst);
int startingday = Integer.parseInt(startingdayst);
int startingmonth = Integer.parseInt(startingmonthst);
int finishingyear = Integer.parseInt(finishingyearst);
int finishingday = Integer.parseInt(finishingdayst);
int finishingmonth = Integer.parseInt(finishingmonthst);

System.out.println(startingyear + "," + startingday + "," + startingmonth );
System.out.println(finishingyear + "," + finishingday + "," + finishingmonth);

int daysLeft = 0;

int daysUntilEnd = 0;

int i = 0;

daysLeft = daysInAMonth(startingmonth, startingyear) - startingday;
daysUntilEnd = finishingday;

for (int monthCount = startingmonth + 1; monthCount <= 12; monthCount++)
{
i += daysInAMonth(monthCount, startingyear);
}       
for (int yearCount = startingyear + 1; yearCount <= finishingyear; yearCount++)
{
    if (isLeapYear(yearCount))
    {
        i = i * 366;
    }
    else
    {
        i = i * 365;
    }
i += daysUntilEnd;

}
    System.out.println(i);
}
private static boolean isLeapYear(int year) {
     boolean isLeapYear = ((year % 4 == 0) && (year % 100 != 0) || (year % 400 == 0));
     return isLeapYear;
    }

private static int daysInAMonth(int month, int year) {
    if (month == 2) 
    {
        if (isLeapYear(year) ) 
        {
            return 29;
        }
        else 
        {
            return 28;
        }

    }
    if (month == 1 || month == 3 || month == 5 || month == 7 || month == 9 || month == 11) {
        return 31;
    }
    return 30;
}
}

1 个答案:

答案 0 :(得分:0)

问题出在这个部分

for (int monthCount = startingmonth + 1; monthCount < finishingmonth; monthCount++)
    {

    i += daysInAMonth(monthCount, startingyear);
    }       

    for (int yearCount = startingyear + 1; yearCount <= finishingyear; yearCount++)
    {
        if (isLeapYear(yearCount))
        {
            i = i + 366;
        }
        else
        {
            i = i + 365;
        }


    }
    i += daysUntilEnd;
    i += daysInAMonth(startingmonth, startingyear)-startingday-1;
        System.out.println(i);

它不完全没有bug,但我希望它可以帮助你查看它出错的地方。这是一个眼睛错误