'if' statement not working?
The 'if' statement part of the code isnt working.
I want it to change the day to 1 and the month to the next month when the day equals 32 or 31 depending on how many days are in the month(32 and 31 referring to the day after the month ends).
DD = day of the month
MM = month
dont worry about DAY and PUs.
Also i wont need to go into the next year so dont worry about helping with that.
Code:
package packageA;
public class d9 {
public static void main(String[]args){
int DD = 9;
int MM = 3;
int DAY = 1;
int PUs = 29;
int count = 1;
System.out.println("MM/DD/YYYY, ###, #PU's\n----------------------");
while(count < 40){
System.out.printf("%02d/%02d/2012, %03d, %05d\n", MM, DD, DAY, PUs);
DD++; DAY++; PUs++;
if(MM == (1|3|5|7|8|10|12)){
if(DD == 32){
DD = 1;
MM += 1;
}
}else{
if(MM == (4|6|9|11)){
if(DD == 31){
DD = 1;
MM += 1;
}
}
}
count++;
}
}
}
THANKS!
Re: 'if' statement not working?
Clean up your code a bit and compartmentalise it so that it becomes easier to understand.
I would use a switch statement instead of what you have done for the number of days in the month, and throw that into a separate method so that you can more clearly identify the problem.
Code:
private static final int MONTH_ERROR = -10;
public int getLastDay(int month, int year) {
switch (month) {
case 1: //jan
case 3: //mar
case 5: //may
case 7: //july
case 8: //aug
case 10: //oct
case 12: //dec
return 31;
case 4: //apr
case 6: //jun
case 9: //sep
case 11: //nov
return 30;
case 2: //feb
return (isLeapYear(year)? 29 : 28);
default:
return MONTH_ERROR;
}
}
public boolean isLeapYear(int year) {
...
}
Once you've done that you can use the method like this:
Code:
public boolean isLastDayOfMonth(int day, int month, int year) {
int lastDay = getLastDay(month, year);
if (day == lastDay) {
return true;
}
return false;
}
And from that decide what to do:
Code:
int day = 10;
int month = 3;
int year = 2012;
if (isLastDayOfMonth(day,month,year)) {
//set to first day of next month
day = 1;
month++;
}
Re: 'if' statement not working?
THANK YOU VERY MUCH SIR!
Although, i don't understand why what i used wouldnt work?
Re: 'if' statement not working?
Quote:
Originally Posted by
Etimer
THANK YOU VERY MUCH SIR!
Although, i don't understand why what i used wouldnt work?
Read this:
Operators (The Java™ Tutorials > Learning the Java Language > Language Basics)
and find the difference between the operator || and |.
Re: 'if' statement not working?
Ahhh, ok. Thank you ozzyman, you've been a big help!
Today has been a breakthrough in java for me!