简体   繁体   中英

Boolean Condition always evaluating true

I'm working on a homework project for an intro Java class in which I am tasked with creating a class and method to test whether an input year is a leap year or not. I've seen plenty of examples of people doing this in one program, but we're required to build the class and then run my professor's Tester file. I've finally gotten everything to compile without error, but every time I run the file I get told that the year is a leap year. I've tried a ton of different things and I can't figure out why the boolean condition at is always evaluating true (or whatever else I'm doing wrong).

My code is below:

public class Year
{
   // declare variable
    private int y;
    private String year;

    // declare constructor
    public Year(String theYear, int year_input)
    {
        y=year_input;
        theYear=year;
    }    

    // ensure y has a value
    public Year(int y)
    {
        y=0;
    } 

    // test if y is a leap year
    public boolean isLeapYear()
    {
             if (y%4==0 && (y/100!=0 || y%400==0))
             { 
                 return true;
             } 
                return false;

    }
} 

and my professor's code is here:

import java.util.Scanner;

public class LeapYearTester{

public static void main(String[] args){

    Scanner input = new Scanner(System.in);
    System.out.println("Please enter a year");
    int year_input = input.nextInt();

    // now make a Year object

    Year theYear = new Year(year_input);

    // now check to see if it's a leap year

    if (theYear.isLeapYear())
        System.out.println("That's a leap year!");
    else
        System.out.println("That's not a leap year!");
    }
}

In your single argument constructor, you are always initializing the year to 0.

Change

public Year(int y)
{
    y = 0;
} 

to

public Year(int y)
{
    this.y = y;
} 

Problem is in your constructor.

You are always initializing year as 0 and not what you get from input.

Also learn to debug :)

In your second constructor, you're always assigning 0 to your input parameter. That makes no sense. Instead you must assign the parameter to your member variable.

Make your constructor

public Year (int y)
{
    this.y = y;
}

instead of always initializing it to 0.

Something is wrong with your year(int) constructor The correct definition should be like

public Year(int y){ this.y = y ;}

What you were doing earlier is initializing the member variable y to 0 Everytime you pass an integer value in your constructor.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM