Я получаю «ноль» при вводе конкретных дат в моем выводе - PullRequest
0 голосов
/ 24 мая 2019

Мой код компилируется и работает отлично, но когда у меня есть даты, которые являются субботами, вывод будет 'нулевым' вместо 'СУББОТЫ'. Ниже будут приведены примеры для дальнейшего объяснения этой проблемы.

Я пытался изменить свое утверждение if для моего метода "getDayOfWeek", но у меня, похоже, нет решения, я также пытался получить помощь от опытного кодера, но они, похоже, борются из-за того, что Java не является их основным языком. ...

Код:

class MyDate {

    // properties of date object
    private int day, month, year;

    // constructor with arguments
    public MyDate(int day, int month, int year) {
        this.day = day;
        this.month = month;
        this.year = year;
    }

    public boolean isDateValid() {
        if (month > 12 || month < 1 || day < 1) { // if values exceed 12 or are negative: return false
            return false;
        } else if (year <= 1582 && month <= 10 && day <= 15) { //     starting date
            //   checking
            return false;
        } // for 31 day months: January, March, May, July, August, October, December
        else if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) {

            if (day > 31) {
                return false;
            }

        } // for 30 day months: April, June, September, November
        else if (month == 4 || month == 6 || month == 9 || month == 11) { 

            if (day > 30) {
                return false;
            }

        } // February check
        else if (month == 2) {

            // leap year check for February
            // 29 days in a leap year
            // 28 days in a common year
            if (isLeapYear()) {
                if (day > 29) {
                    return false;
                }

            } else {
                if (day > 28) {
                    return false;
                }
            }
        }
        return true;
    }

    // checks if input year is leap year
    private boolean isLeapYear() {
        if (year % 4 != 0) {
            return false;
        } else if (year % 400 == 0) {
            return true;
        } else if (year % 100 == 0) {
            return false;
        } else {
            return true;
        }
    }

    // method returns the day of MyDate object
    public int getDay() {
        return day;
    }

    // parameter for day to set
    public void setDay(int day) {
        this.day = day;
    }

    // method returns the month of MyDate object
    public int getMonth() {
        return month;
    }

    // parameter for month
    public void setMonth(int month) {
        this.month = month;
    }

    // method returns the year of MyDate object
    public int getYear() {
        return year;
    }

    // parameter for year
    public void setYear(int year) {
        this.year = year;
    }

    // method returns all variables: day/month/year of MyDate object 
    public String toString() {
        return day + "/" + month + "/" + year;
    }
}

public class MyCalendar {

    //enums for days of week
    public static enum Day {
        SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY,  SATURDAY;
    };

    //enums for month of year
    public static enum Month {
        JANUARY, FEBRUARY, MARCH, APRIL, MAY, JUNE, JULY, AUGUST, SEPTEMBER, OCTOBER, NOVEMBER, DECEMBER;
    };

    //enums for week number of month
    public static enum Week {
        FIRST, SECOND, THIRD, FOURTH, FIFTH;
    };

    //to store Date object
    private MyDate date;

    //constructor taking mydate object
    public MyCalendar(MyDate enteredDate) {
        this.date = enteredDate;
    }

    //main method 
    public static void main(String[] args) {

        boolean dateValid = false; //valid date false
        Scanner input = new Scanner(System.in); //scanner for input
        MyDate enteredDate = null;

        //till valid date found
        while (!dateValid) {
            System.out.print("Enter the date as day month year : ");
            //taking input and creating date output
            enteredDate = new MyDate(input.nextInt(), input.nextInt(), input.nextInt());
            //validating date input

            if (enteredDate.isDateValid()) { //if valid
                MyCalendar myCalendar = new MyCalendar(enteredDate); 
                //creating calendar table

                myCalendar.printDateInfo(); //printing date info
                myCalendar.printCalendar(); //printing calendar
                dateValid = true; //setting validate to true 
            } else {
                System.out.println(enteredDate + " is not a valid date, please re-input a valid date: ");
            }
        }

        input.close();
    }

    // returns number of days in current month
    private int getNumberOfDays() {
        int days = 31;
        int month = date.getMonth();
        if (month == 4 || month == 6 || month == 9 || month == 11)
            days = 30;
        return days;
    }

    //print calendar of input month
    public void printCalendar() {
        System.out.println("\n\nThe Calendar of "+Month.values()[date.getMonth()-1]+" "+date.getYear()+" is :");
        int numberOfMonthDays = getNumberOfDays();
        Day firstWeekdayOfMonth = getDayOfWeek(1, date.getMonth(), date.getYear());
        int weekdayIndex = 0;
        System.out.println("Su Mo Tu We Th Fr Sa");
        // The order of days depends on the input of date 
        // to display output of calendar

        for (int day = 0; Day.values()[day] != firstWeekdayOfMonth; day++) {
            System.out.print("   "); // this loop to print the first day in the
            // correct place
            weekdayIndex++;
        }
        for (int day = 1; day <= numberOfMonthDays; day++) {

            if (day < 10) 
                System.out.print(day + " ");
            else
                System.out.print(day);
            weekdayIndex++;
            if (weekdayIndex == 7) {
                weekdayIndex = 0;
                System.out.println();
            } else {
                System.out.print(" ");
            }
        }
        System.out.println();
    }

    //method to print about date information in literal form
    public void printDateInfo() {
        System.out.println(date + " is a " + getDayOfWeek(date.getDay(), date.getMonth(), date.getYear())
        + " located in the " + Week.values()[getWeekOfMonth() - 1] + " week of "
        + Month.values()[date.getMonth() - 1] + " " + date.getYear());
    }

    /*
     * gets day of the week, returns enum type Day
     *
     * Zellar's congruence to calculate the day of week
     * for any given date after October 15 1582
     * (h) = (q+(13*(m+1)/5)+K+(K/4)+(J/4)+5J)%7 ,q- day of month,
     * m- month, k = year of century (year%100), J = (year/100)
     */
    public Day getDayOfWeek(int day, int month, int year) {
        int q = day;
        int m = month;

        if (m < 3) {
            m = 12 + date.getMonth();
            year = year - 1;
        }
        int K = year % 100;
        int J = year / 100;
        //calculating h value
        int h = (q + (13 * (m + 1) / 5) + K + (K / 4) + (J / 4) + 5 * J) % 7;
        Day output = null;
        if (h < Day.values().length && h > 0) {
            output = Day.values()[h - 1]; //getting respective  enum value
        }
        return output; //returning enum value
    }

    // get week number of current date
    public int getWeekOfMonth() {
        int days = date.getDay();
        int weeks = days / 7;
        days = days % 7;
        if (days > 0)
            weeks++;
        return weeks;
    }

}

Ожидаемые результаты:

java MyCalendar 29/02/2019
29/02/2019 in not a valid date, please re-input a valid date:         25/05/2019
25/05/2019 is a Saturday and located in the fourth week of May 2019
The calendar of May 2019 is:
SUN MON TUE WED THU FRI SAT
            1   2   3   4  
5   6   7   8   9   10  11
12  13  14  15  16  17  18
19  20  21  22  23  24  25
26  27  28  29  30  31

Фактические результаты:

25/05/2019 is a null located in the FOURTH week of MAY 2019

The calendar of May 2019 is:
SUN MON TUE WED THU FRI SAT
            1   2   3   4  
5   6   7   8   9   10  11
12  13  14  15  16  17  18
19  20  21  22  23  24  25
26  27  28  29  30  31

Результаты другой даты (это не суббота):

24/05/2019 is a FRIDAY located in the FOURTH week of MAY 2019

The calendar of May 2019 is:
SUN MON TUE WED THU FRI SAT
            1   2   3   4  
5   6   7   8   9   10  11
12  13  14  15  16  17  18
19  20  21  22  23  24  25
26  27  28  29  30  31

Указанная проблема: Вывод выводит ноль во все даты, которые находятся в день субботы, в то время как другие даты, которые не являются субботой, достигнут нужного правильного вывода.

Ответы [ 2 ]

1 голос
/ 24 мая 2019
if (h < Day.values().length && h > 0) {

должно измениться на

if (h < (Day.values().length + 1) && h > 0) {
0 голосов
/ 24 мая 2019
  • Если это для производственного кода, комментарий Бэзила Бурка верен: вы не должны разрабатывать свой собственный класс MyDate, а полагаться на встроенный класс LocalDate.
  • Если, с другой стороны, как я полагаю, это упражнение по программированию, оно прекрасно, и нет никаких причин (которые я вижу), почему вы не должны пробиваться через это.

Ваша формула для вычисления дня недели:

    //calculating h value
    int h = (q + (13 * (m + 1) / 5) + K + (K / 4) + (J / 4) + 5 * J) % 7;

(Кроме того, пожалуйста, найдите более подходящие имена переменных, а также соблюдайте соглашение об именах Java: имя переменной не может быть заглавной буквой.) Я не понимаю формулу, но при условии, что она правильная, она вычисляет день недели как 0 = суббота, 1 = воскресенье до 6 = пятница. Чтобы использовать этот номер для поиска в вашем перечислении Day, используйте

        output = Day.values()[(h + 6) % 7]; //getting respective  enum value

Поскольку h всегда будет неотрицательным и меньше 7, вам не нужно вмещающее выражение if. Просто присвойте output безоговорочно. С этими изменениями я получаю

Enter the date as day month year : 25 5 2019
25/5/2019 is a SATURDAY located in the FOURTH week of MAY 2019


The Calendar of MAY 2019 is :
Su Mo Tu We Th Fr Sa
         1  2  3  4 
5  6  7  8  9  10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
...