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;
}
}
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)));
}
Related
So I created LeapYearCal this on If else statement I learn switch statement I want to recreate it using switch.
Somehow my condition for leap is working, but I want to add condition like value must be in 1- 9999 only else it'll returned false. but when my code is incorrect How do I solve the problem?
public static boolean isLeapYear(int year)
{
switch ( year % 4)
{
case 0:
if (year % 100 == 0)
{
if ( (year % 400 == 0) )
{
if (year > 0)
{
if (year <= 9999)
{
return true;
}
else
return false;
}
else
return false;
}
else
return false;
}
else
return true;
default:
break;
}
return false;
I want to the output "True" if the year is Leap year and it's range 1-9999 else "False" if it is not in range regardless if its leap year
Using switch-case statement in this use-case is inappropriate. This solution is based on this code :
public static boolean isLeapYear(int year){
boolean flag = false;
if (year > 0 && year < 10000)
{
flag = false;
}
else if(year % 400 == 0)
{
flag = true;
}
else if (year % 100 == 0)
{
flag = false;
}
else if(year % 4 == 0)
{
flag = true;
}
else
{
flag = false;
}
return flag;
}
I have 1 constructor and 1 factory method for my Date class. The first one just have 3 int parameter represent month, day and year. And the second one, I provide it in case user give string as one parameter to represent month/day/year.
As you can see in the main(), I forget to call parseIt, the factory method. But compiler still provide correct result. So question is: can JAVA call this factory method implicitly?
Please take a look the 1st constructor and 2nd factory methods:
import java.io.*;
class Date {
private int month;
private int day;
private int year;
public Date(int month, int day, int year) {
if (isValidDate(month, day, year)) {
this.month = month;
this.day = day;
this.year = year;
} else {
System.out.println("Fatal error: Invalid data.");
System.exit(0);
}
}
public static Date parseIt(String s) {
String[] strSplit = s.split("/");
int m = Integer.parseInt(strSplit[0]);
int d = Integer.parseInt(strSplit[1]);
int y = Integer.parseInt(strSplit[2]);
return new Date(m, d, y);
}
public static boolean isLeapYear(int year) {
if (year%4 != 0) {
return false;
} else if (year%100 == 0 && year%400 != 0) {
return false;
}
return true;
}
public static int daysInMonth(int month, int year) {
if (month == 2) {
if (isLeapYear(year)) {
return 29;
} else {
return 28;
}
} else if (month == 4 || month == 6 || month == 9 || month == 11) {
return 30;
} else {
return 31;
}
}
public static boolean isValidDate(int month, int day, int year) {
if (year < 1 || year > 9999 || month <= 0 || month > 12 || day <= 0) {
return false;
} else if (day > daysInMonth(month, year)) {
return false;
}
return true;
}
public static void main(String[] argv) {
Date d1 = new Date(1, 1, 1);
System.out.println("Date should be 1/1/1: " + d1);
d1 = new Date("2/4/2");
System.out.println("Date should be 2/4/2: " + d1);
}
}
No, it will not. There is no constructor which takes in a string, so it would throw a syntax error. In order to make it work, you would have to define a constructor which takes in a String parameter performs the same logic as the parseIt(String) function.
Day Validation is always returning the illegal argument exception and never setting the day as inputed especially when trying to input 29 for february in a leap year. i've been trying to find the error for a long time now and just gave up. thanks for your help in advance.
import java.util.Calendar;
public class DateOfBirth
{
private int day;
private int month;
private int year;
private Calendar cld = Calendar.getInstance();
public DateOfBirth()
{
this(0,0,0);
}
public DateOfBirth(int a,int b,int c)
{
setDay(c);
setMonth(a);
setYear(b);
}
public void setDay(int a)
{
if( getMonth()==2 && (getYear() % 4 == 0 && (getYear() % 100 != 0 || getYear() % 400 == 0))&& a == 29)
day = a;
else if(getMonth() == 2 && a <= 28)
day = a;
else if(getMonth() == 1 || getMonth() == 3 || getMonth() == 5 || getMonth() == 7 || getMonth() == 8 || getMonth() == 10 || getMonth() == 12 && a < 31)
day = a;
else if(getMonth() == 4 || getMonth() == 6 || getMonth() == 9 || getMonth() == 11 && a < 30)
day = a;
else
throw new IllegalArgumentException("Day Out Of Bounds.");
}
public void setMonth(int b)
{
if( b > 0 && b <= 12)
month = b;
else
throw new IllegalArgumentException("Month Out of Bounds.");
}
public void setYear(int c)
{
if( c > (cld.get(Calendar.YEAR) - 150) && c < cld.get(Calendar.YEAR))
year = c;
else
throw new IllegalArgumentException("Year Out of Bounds.");
}
public int getDay()
{
return day;
}
public int getMonth()
{
return month;
}
public int getYear()
{
return year;
}
#Override
public String toString()
{
return String.format("Date Of Birth: %02d/%02d/%d",getDay(),getMonth(),getYear());
}
}
You're calling setDay first, before you call setMonth or setYear... which means setDay doesn't know which month and year you're talking about. It can't possibly validate that the day is correct without that information.
You could just switch the order of the setter calls:
setYear(b);
setMonth(a);
setDay(c);
However:
Your parameterless constructor tries to set an invalid value (day=0, month=0 - what?) so what's the point of having it?
You should definitely rename your constructor parameters to be meaningful (how is anyone meant to know that b represents the year, for example?)
Being able to set each property individually makes this fragile... for example, you could set the month to January, the day to 30, then the month to February... all without any validation errors, leaving you with February 30th. That's basically what's happening at the moment in your constructor, but you could do that from outside, too.
I would suggest that you make your class immutable if at all possible. Then you just need to validate in the constructor. Consider refactoring it to:
// TODO: Think of a decent name. Not DateOfBirth because it's just representing
// a date, and not Date as that conflicts with java.util.Date.
public final class GregorianDate {
private final int year, month day;
public GregorianDate(int year, int month, int day) {
validate(year, month, day);
this.year = year;
this.month = month;
this.day = day;
}
private static void validate(int year, int month, int day) {
// TODO: The validation
}
// getters, toString, hashCode, equals, and possibly implement
// Comparable<GregorianDate> too.
}
Of course, this is assuming this is just an exercise - normally you'd use appropriate date/time APIs that are already provided to you - ideally avoiding java.util.Date/Calendar and using Joda Time or the Java 8 java.time API.
your logic here is flawed I added parenthesis to fix it
public void setDay(int a)
{
if( getMonth()==2 && (getYear() % 4 == 0 && (getYear() % 100 != 0 || getYear() % 400 == 0))&& a == 29)
day = a;
else if(getMonth() == 2 && a <= 28)
day = a;
else if((getMonth() == 1 || getMonth() == 3 || getMonth() == 5 || getMonth() == 7 || getMonth() == 8 || getMonth() == 10 || getMonth() == 12) && a < 31)
day = a;
else if((getMonth() == 4 || getMonth() == 6 || getMonth() == 9 || getMonth() == 11) && a < 30)
day = a;
else
throw new IllegalArgumentException("Day Out Of Bounds.");
}
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
why am i getting the following error message when i call the toString of class Date from toString of class Time2 ?
Exception in thread "main" java.lang.NullPointerException
at Exerciseschpt8.Time2.toString(Time2.java:111)
at Exerciseschpt8.Time2Test.main(Time2Test.java:18)
package Exerciseschpt8;
public class Date{
private int month; // 1-12
private int day; // 1-31 based on month
private int year; // any year
public Date(){
this(0,0,0);
}
public Date(int theMonth, int theDay, int theYear) {
month = checkMonth(theMonth); // validate month
year = theYear; // could validate year
day = checkDay(theDay); // validate day
System.out.printf("Date object constructor for date %s\n", this);
}
private int checkMonth(int month) {
if (month > 0 && month <= 12) // validate month
return month;
else // month is invalid
{
System.out.printf("Invalid month (%d) set to 1.", month);
return 1; // maintain object in consistent state
} // end else
} // end method checkMonth
// utility method to confirm proper day value based on month and year
private int checkDay(int day) {
int[] daysPerMonth = { 0, 31, 28, 31, 30, 31, 30, 28, 31, 30, 31, 30,
31 };
// check if day in range for month
if (day > 0 && day <= daysPerMonth[month])
return day;
// check for leap year
if (month == 2 && day == 29
&& (year % 400 == 0 || (year % 4 == 0 && year % 100 != 0)))
return day;
System.out.printf("Invalid day (%d) set to 1.", day);
return 1; // maintain object in consistent state
} // end method checkDay
// return a String of the form month/day/year
public String toString() {
return ""+month+"/"+ day+"/"+year;
} // end method toString
public int nextDay() {
int testDay = day + 1;
if (checkDay(testDay) == testDay)
day = testDay;
else {
day = 1;
//nextMonth();
}
return day;
}
public int nextMonth() {
if (1 == month)
month++;
return month = 1;
}
public String toDateString() {
return month + "/" + day + "*/" + year;
}
}
package Exerciseschpt8;
import Exerciseschpt8.Date;
public class Time2 {
Date dateX;
private int hour; // 0 - 23
private int minute; // 0 - 59
private int second; // 0 - 59
public Time2() {
this(0, 0, 0);
}
public Time2(int h) {
this(h, 0, 0);
}
public Time2(int h, int m) {
this(h, m, 0);
}
public Time2(int h, int m, int s) {
setTime(h, m, s);
}
public Time2(Time2 time) {
this(time.getHour(), time.getMinute(), time.getSecond());
}
public boolean setTime(int h, int m, int s) {
boolean hourValid, minuteValid, secondValid;
hourValid = setHour(h); // set the hour
minuteValid = setMinute(m); // set the minute
secondValid = setSecond(s); // set the second
return (hourValid && minuteValid && secondValid);
}
public boolean setHour(int h) {
// hour = ((h >= 0 && h < 24) ? h : 0);
if (h >= 0 && h < 24) {
hour = h;
return true;
} else {
hour = 0;
return false;
}
} // end method setHour
public boolean setMinute(int m) {
// minute = ((m >= 0 && m < 60) ? m : 0);
if (m >= 0 && m < 60) {
minute = m;
return true;
} else {
minute = 0;
return false;
}
} // end method setMinute
public boolean setSecond(int s) {
// second = ((s >= 0 && s < 60) ? s : 0);
if (s >= 0 && s < 60) {
second = s;
return true;
} else {
second = 0;
return false;
}
} // end method setSecond
public int getHour() {
return hour;
} // end method getHour
public int getMinute() {
return minute;
} // end method getMinute
public int getSecond() {
return second;
} // end method getSecond
// Tick the time by one second
public void tick() {
setSecond(second + 1);
if (second == 23)
incrementMinute();
}
public void incrementMinute() {
setMinute(minute + 1);
if (minute == 25)
incrementHour();
}
public void incrementHour() {
setHour(hour + 1);
if (hour == 0)
dateX.nextDay();
}
public String toString() {
return + hour + ":" + minute + ":" + second + "\n"+dateX.toString();
}
package Exerciseschpt8;
public class Time2Test {
public static void main(String[] args) {
Time2 t1 = new Time2(2,15,23); // 00:00:00
/
Date d1 = new Date(10,23,1973);
//System.out.println(d1.toDateString());
System.out.println("Constructed with:");
System.out.println("t1: all arguments defaulted");
//System.out.printf(" %s\n", t1.toUniversalString());
System.out.printf(" %s\n", t1.toString());
}
}
You are nowhere initializing dateX in your Time2 class and using a method on it (dateX.toString()) in the toString() method of Time2 class. That is causing the valid NullPointerException.
To fix the issue, intialize dateX as appropriate to your program.
In the line Date dateX; you are declaring dateX, but you aren't initializing it, so it's a null pointer. To initialize it, change the line to Date dateX = new Date();
I have an assignment for school to make a program which results in either true or false. It's about wether a year is a leap year or not. The problem I have at the moment is that i'm using a public static boolean instead of a public boolean.
This is my code:
public class Assignment {
static boolean isLeapYear;
public static void main(String[] args)
{
int year = 2000;
isLeapYear(year);
}
public static boolean isLeapYear(int year) {
if (((year/100)%4 == 0 && year%4 ==0) || (year % 400 == 0))
isLeapYear = true;
else
isLeapYear = false;
System.out.println(isLeapYear);
return isLeapYear;
}
}
The int year is 2000 at the moment but the rules are like this:
A leap year is a year wich can be divided by 4 unless the year is the beginning of a new century (1700, 1800, 1900.....). So even though you can divide 1900 by 4 you can't divide it by 400 so it's false.
So again the question: What do I need to do so i'm able to use a public boolean instead of a public static boolean?
You would need to create an instance of your class to invoke that method from your main method, if you want to make your method non-static. And then you can make your isLeapYear variable non-static: -
boolean isLeapYear;
public static void main(String[] args)
{
int year = 2000;
new Assigment().isLeapYear(year);
}
public boolean isLeapYear(int year) {
// access isLeapYear as `this.isLeapYear` or just `isLeapYear`
}
But, precisely, you don't need to store your result in a boolean variable. If you want to return a boolean value of some expression, then you can just return that expression.
So, just having this code in your method would also work fine, and it is more readable, and let that method be static: -
return (((year/100)%4 == 0 && year%4 ==0) || (year % 400 == 0))
And from your main call: -
System.out.println("Year : " + year + ", is leap year: " + isLeapYear(year));
You don't need to store this result anywhere.
Use:
public static boolean isLeapYear(int year)
{
return (((year/100)%4 == 0 && year%4 ==0) || (year % 400 == 0));
}
Static methods can only access static variables, only instance methods can access instance methods, which you can infer if you think Object oriented.
Just in case you should store the Boolean isLeapYear
public class Testing {
boolean isLeapYear;
public static void main(String[] args)
{
int year = 2000;
new Testing().isLeapYear(year);
}
public boolean isLeapYear(int year) {
if (((year/100)%4 == 0 && year%4 ==0) || (year % 400 == 0))
isLeapYear = true;
else
isLeapYear = false;
System.out.println(isLeapYear);
return isLeapYear;
}
}
Does your assignment say it has to be stored in a class or instance variable? If not, there is no need for public boolean isLeapYear or public static boolean isLeapYear, just return the result of the calculation and store it in a local variable like this:
public static boolean isLeapYear(int year) {
return ((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0);
}
in main method:
int year = 2000;
boolean isLeap = isLeapYear(year);
System.out.println(isLeap);