Reputation: 13
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!");
}
}
Upvotes: 1
Views: 738
Reputation: 35
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.
Upvotes: 0
Reputation: 34
Make your constructor
public Year (int y)
{
this.y = y;
}
instead of always initializing it to 0.
Upvotes: 0
Reputation: 10112
Problem is in your constructor.
You are always initializing year as 0 and not what you get from input.
Also learn to debug :)
Upvotes: 1
Reputation: 531
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.
Upvotes: 0
Reputation: 394146
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;
}
Upvotes: 5