swennemen
swennemen

Reputation: 955

My boolean of an object gets changed without the program doing anything

I've been debugging for hours, and I finally found where the problem is. NOW I have to fix it :)

I thinks something strange happens.

I'm creating an date app, where I calculate which day it is (with leapyear corrections etc).

I have a method, where I take a Year object.

private int totalDays(Year yearnumber) {
    System.out.println("Boolean check 1: " + yearnumber.getLeapYear()); 

    //calculate days for whole year//
    int daysWholeYear = 0; 
    for (int i = year.getYearZero(); i < yearnumber.getYear(); i++) {
        // here i will add all the days (366) from the leapyears //
        if (yearnumber.isLeapYear(i) == true) {
            totalDays += year.getLengthyear() + 1; 
            System.out.println("Boolean check 2: " + yearnumber.getLeapYear()); 
        } else {
            totalDays += year.getLengthyear();  
        }
    }

    System.out.println("Boolean check 3: " + yearnumber.getLeapYear()); 

My first two boolean checks are ok.

Code (without the boolean check looped in the for loop)

Boolean check 1: true
Boolean check 2: true
Boolean check 3: false

I need my Boolean in the next lines of my method, where I calculate the days of the months (non whole years). However, my program now thinks that the year is not a leap year and therefore makes wrong calculations.

Because this Boolean changes in my program, the rest of my calculation are off. Can someone explain my why this happens? :)

EDIT: code from my year class:

public class Year {
    private static int yearzero = 1753; 
    private static int lengthYear = 365; 
    private int year; 
    private boolean leapYear; 
    private int startYear; //are used for an interval calculations
    private int eindYear; // 


    public Year(int year) {
        this.year = year; 
        this.leapYear = isLeapYear(year);
    }

    boolean isLeapYear(int year) {
        return leapYear = (year % 400 == 0) || 
        ((year % 100) != 0 && (year % 4 == 0));
    }

    public int getYear(){
        return year;  
    }

    public int getYearzero () {
        return yearZero; 
    }

    public int getLengthYear() {
        return lengthYear; 
    }

    public boolean getLeapYear() {
        return leapYear; 
   }

}

Upvotes: 0

Views: 70

Answers (1)

Levente Kurusa
Levente Kurusa

Reputation: 1866

Your isLeapYear function sets the object's leapYear variable. This is because the yearnumber.isLeapYear(i) == true will fail, and yearnumber.leapYear will be set to false.

Change

 boolean isLeapYear(int year) {
        return leapYear = (year % 400 == 0) || 
        ((year % 100) != 0 && (year % 4 == 0));
    }

to:

 boolean isLeapYear(int year) {
        return ((year % 400 == 0) || 
        ((year % 100) != 0 && (year % 4 == 0)));
    }

Upvotes: 3

Related Questions