How to do a date validation with leap years

I'm doing a date validation program in my Java class, and well it's pretty hard (for me that is). I have to be able to type in a date, have it say whether it's a leap year or not, and print out the number of days in the month. It seems pretty straight forward, but I get confused on trying to do the 'if else' statements and even the simplest things like getting the day prompting to work. >< The years I'm doing only goes through 1000 to 1999, so that's why those numbers are there. The program isn't complete, so if anyone could help show me what I'm doing wrong in the areas I'm working on then I'd appreciate it...and I'm still kind of in the basics of Java so if you do hint me with some code then I'd appreciate it if it was stuff that's not too advanced so yea.
// Dates.java
// Determine whether a 2nd-millenium date entered by the user
// is valid
import java.util.Scanner;
public class Dates
public static void main(String[] args)
int month, day, year; //date read in from user
int daysInMonth; //number of days in month read in
boolean monthValid, yearValid, dayValid; //true if input from user is valid
boolean leapYear; //true if user's year is a leap year
Scanner scan = new Scanner(System.in);
//Get integer month, day, and year from user
System.out.print("Type in the month: " );
          month = scan.nextInt();
System.out.print("Type in the day: " );
          day = scan.nextInt();
System.out.print("Type in the year: " );
          year = scan.nextInt();
//Check to see if month is valid
if (month >= 1)
month = month;
else
if (month <= 12)
month = month;
else;
//Check to see if year is valid
if (year >= 1000)
year = year;
else
if (year <= 1999)
year = year;
else;
//Determine whether it's a leap year
//Determine number of days in month
if (year == 1 || 3 || 5 || 7 || 8 || 10 || 12)
     System.out.println (Number of days in month is 31);
     else (year == 4 || 6 || 9 || 11)
     System.out.println (Number of days in month is 30);
//User number of days in month to check to see if day is valid
//Determine whether date is valid and print appropriate message
// Dates.java
// Determine whether a 2nd-millenium date entered by the user
// is valid
import java.util.Scanner;
public class Dates
public static void main(String[] args)
int month, day, year; //date read in from user
int daysInMonth; //number of days in month read in
boolean monthValid, yearValid, dayValid; //true if input from user is valid
boolean leapYear; //true if user's year is a leap year
Scanner scan = new Scanner(System.in);
//Get integer month, day, and year from user
System.out.print("Type in the month: " );
          month = scan.nextInt();
System.out.print("Type in the day: " );
          day = scan.nextInt();
System.out.print("Type in the year: " );
          year = scan.nextInt();
//Check to see if month is valid
if (month >= 1)
month = month;
else
if (month <= 12)
month = month;
else;
//Check to see if year is valid
if (year >= 1000)
year = year;
else
if (year <= 1999)
year = year;
else;
//Determine whether it's a leap year
//Determine number of days in month
if (year == 1 || 3 || 5 || 7 || 8 || 10 || 12)
     System.out.println (Number of days in month is 31);
     else (year == 4 || 6 || 9 || 11)
     System.out.println (Number of days in month is 30);
//User number of days in month to check to see if day is valid
//Determine whether date is valid and print appropriate message
}

Here are some helpfull hints for you:
1. Your code is really hard to read, there are two main reasons for this. First, your indentation sucks. Second, you seem to be fascinated with saving two (ok four if you count the shift key) keypresses to avoid using { and }.
2. Not using the brackets (you know { and } which you like to avoid) also is causing your code to do some stuff you don't realize or want to happen, or at least it would be if your code compiled.
3. If statements require arguements, "year == 1" is an arguement, "3" is not an arguement. Each operator like the or operator ("||") is essentially a new if and requires a complete arguement. So the following code peice:
if (year == 1 || 3 || 5 || 7 || 8 || 10 || 12)Literally translates to if year equals 1 or if 3 or if 5 or if 7 or if 8 or if 10 or if 12. Doesn't make much sense in english, and it doesn't make much sense in Java either.
4. I am pretty sure "year" is not the variable you want in the code snippet above (the one used in hint 3), especially considering years 1, 3, 5, 7, 8, 10, and 12 are not between 1000 and 1999. You need to be really carefull not make these kind of mistakes when coding, because they are by far the hardest to track down and fix later since they don't really throw up any flags or anything at compile or run time. Take your time and think thuroughly about each line of code while coding it, it will save you tons of time in the long run.
5. What exactly do you expect statements like "month = month;" to do? That translates as make month equal to month. Do you go to the bank and say " I have exactly $3.56 in my pocket, so I would like to deposite all $3.56 and then withdraw $3.56 and put it back in my pocket"? How do you think the teller would look at you? Teller would probably do it, but the teller would feel like he/she wasted time with you and that you are not really right in the head. Java feels the same way when you make it do the same thing, and you love to do it.
6. Code like the following is all wrong, and for more reasons than pointed out in hint 5.
if (month >= 1)
month = month;
else
if (month <= 12)
month = month;
else;Let's say someone put 13 in as the month. It passes the first check because 13 is greater than or equal to 1. so month which is 13, now gets set to 13 (gee that was effective). Now we hit the else and things get confusing because you didn't use brackets or proper indentation (hint 1) so we don't know what your real intent was. Did you mean else do nothing, and the next if statement is then executed, or did you mean to just run the next if statement if the else condition was met? Fortunatly it doesn't matter here because the next if statement is failed anyways since 13 is not less than or equal to 12.
So, we leave this code with month ebing 13, wait when did we add a 13th month to the calendar? Are you using the Jewish calendar? Could be, except even if I put 1234567 as the month your code would except it as valid, and I know no calendar with that many months. Try writing this in english first and translating it to jave, like i would probably say "if the month is greater than or equal to 1 and less than or equal to 12 then the month is valid." Course now what do you do if it is invalid? Hmm, maybe I would actually say "while the month is less than 1 or greater than 12 ask the user for the month" until they get it right.
There are a few other problems, but most of them are probably things you haven't learned yet, and they are not show stoppers so we will let them fly. You already have a lot of work to do to make this better. But I do have one more really really big usefull hint for you:
Never, ever, under any circumstances, should you ever ask in any way or even hint at asking for someone else to provide code solutions to your problems. So "so if you do hint me with some code then I'd appreciate it if it was stuff that's not too advanced " was a very bad thing to do, but fortunatly for you you followed it with proof you were trying to write the code yourself. Had the code you provided not been so full of problems it was obvious a beginner wrote it, you would probably have gotten much less cordial responses. I would seriously consider avoiding any implication of wanting code, at least until you become a regular poster here and people know you are not just looking to get your homework done for you.
Hope some of this helps.
JSG

Similar Messages

  • How to delete multiple data domains with single step ?

    how to delete multiple data domains with single step ?

    You can go to your Endeca-Server domain home e.g.($WEBLOGIC-HOME$/user_projects/domains/endeca_server_domain/EndecaServer/bin)
    run
    [HOST]$ ./endeca-cmd.sh list-dd
    default is enabled.
    GettingStarted is enabled.
    endeca is enabled.
    BikeStoreTest is enabled.
    create a new file from the output just with the domains that you want to delete and then create a loop
    [HOST]$ vi delete-dd.list
    default
    GettingStarted
    endeca
    BikeStoreTest
    [HOST]$ for i in $(cat delete-dd.list); do; ./endeca-cmd.sh delete-dd $i; done
    Remember that this can not be undone, unless you have a backup.

  • How to convert a date field with format (dd,mm,yyyy) to format (mm,dd,yyyy)

    Hello.
    How to convert a date field with format (dd,mm,yyyy) to format (mm,dd,yyyy)
    I have text field which has a databind to a date field. When I click on it, we can select the date, it is added on the format (dd,mm,yyyy). When I want to insert this date field to a database It doesnu2019t allow me to do it because it will only accept date field on the format (mm,dd,yyyy)
    I tried to store this format on a date variable and I get a message saying that is impossible to convert a string into a date.
    Regards,
    Jose

    Hi Jose,
    usually you format strings in c# like
    string.Format("{0:yyyyMMdd}", insertyourstring);
    in your case
    string.Format("{0:MM/dd/yyyy}", insertyourstring);
    [look here|http://idunno.org/archive/2004/14/01/122.aspx]
    there are more details
    if everything fails split the string with Mid()
    or ask me
    lg David

  • Check data valid with Java Script

    Hi, every one,
    I made a jsp program and just to check if the data is valid before submit. My problem is even the data is invalid, it still go to next jsp page and display alert message at the same time. But I think if the data is invalid, we can't go to next jsp page. So, any one can tell me what's wrong with my program.
    Thanks in advance.
    The source code is as follows:
    <HTML><HEAD>
    <TITLE>TEST PROGRAM</TITLE>
    <SCRIPT LANGUAGE="JavaScript">
    function validate(){
         if(document.form1.yourname.value.length < 1){
              alert("please enter your full name");
              return false;
         if(document.form1.address.value.length < 3){
              alert("please enter your address.");
              return false;
         if(document.form1.phone.value.length < 3){
              alert("please enter your phone number");
              return false;
         return true;
    </SCRIPT>
    </HEAD>
    <BODY>
    <H1>FORM EXAMPLE</H1>
    Enter the following information. When you press the Display button,
    the data you entered will be validated, then sent by e-mail.
    <form name="form1" action="a2.jsp" enctype="text/plain" onSubmit="validate();">
    <p>
    <b>Name:</b><input type="text" length="20" name="yourname">
    <p>
    <b>Address:</b>
    <input type="text" length="30" name="address">
    <p>
    <b>Phone:</b><input type="text" length="15" name="phone">
    <p>
    <input type="SUBMIT" value="Submit">
    </FORM>
    </BODY>
    </HTML>

    Hi,
    I have another question. If i have a menu as follows and I just want to check the data valid on the current page. I mean, only value=1, 2,3 is valid, value=0 is invalid. How can I do?
    <td valign="middle" width="63%"> <font face="Arial, Helvetica, sans-serif" size="2">
    <select name="type">
    <option value="0">Please Select One of The Following Reasons</option>
    <option value="1">Exchange</option>
    <option value="2">Refund</option>
    <option value="3">Wrong Product</option>
    </select>
    </font></td>
    </tr>
    Thanks.
    peter

  • How to make custom data validation on standard form.

    Hi,
    I have some little OAF experience. I have extended VO so far but I am still newbie.
    I need to make custom data validation on standard form.
    I Oracle Credit Management module on "Create Credit Application: Applicant" form I need
    to validate chosen currency against customer setup (whether there is customer profile amount for the currency).
    The page is /oracle/apps/ar/creditmgt/application/webui/ARCMCREDITAPPPAGE
    There are controllers on the page:
    oracle.apps.ar.creditmgt.application.webui.creditAppContentFooterCO 115.14.15104.2
    oracle.apps.ar.creditmgt.application.webui.creditApplicationPageCO 115.6
    oracle.apps.ar.creditmgt.application.webui.creditAppRegion2CO 115.13.15104.2
    oracle.apps.ar.creditmgt.application.webui.creditApplicationCO 115.8.15104.3
    oracle.apps.ar.creditmgt.application.webui.creditAppRegion1CO 115.28.15104.4
    oracle.apps.ar.creditmgt.application.webui.creditAppBusBackCO 115.6
    oracle.apps.ar.creditmgt.application.webui.OCMApplicantInfoRNCO 115.4
    creditApplicationPageCO is pageLayout controller.
    Please direct me how to achieve it.
    Which controller should I extend (if any)?
    How to get values from the page (customer site id, currency) and how to run custom sql in my CO class ?
    Regards,
    Marcin

    Hi Marcin,
    You have to find your GO button is handled in which standard controller, (if you click on the about this page, you should be able to identify the controller,
    or you can download all the controller .class files and decompile and check the logic).
    Then extend that controller(which has the Go button logic, you can see how it has been handled.),
    The usual way to check is
    if(pageContext.getParameter('<Go button name>') !=null)
    Since you want to validate first your custom validation, in the extended controller ProcessFormRequest
    dont call the super.processFormRequest unless your validation is success.
    Call the super at the end.
    Inside your extended controller you have to find your AM and then your required ViewObject to get the user entered values.
    Thanks,
    With regards,
    Kali.
    OSSi.

  • How to load unicode data files with fixed records lengths?

    Hi!
    To load unicode data files with fixed records lengths (in terms of charachters and not of bytes!) using SQL*Loader manually, I found two ways:
    Alternative 1: one record per row
    SQL*Loader control file example (without POSITION, since POSITION always refers to bytes!)<br>
    LOAD DATA
    CHARACTERSET UTF8
    LENGTH SEMANTICS CHAR
    INFILE unicode.dat
    INTO TABLE STG_UNICODE
    TRUNCATE
    A CHAR(2) ,
    B CHAR(6) ,
    C CHAR(2) ,
    D CHAR(1) ,
    E CHAR(4)
    ) Datafile:
    001111112234444
    01NormalDExZWEI
    02ÄÜÖßêÊûÛxöööö
    03ÄÜÖßêÊûÛxöööö
    04üüüüüüÖÄxµôÔµ Alternative2: variable length records
    LOAD DATA
    CHARACTERSET UTF8
    LENGTH SEMANTICS CHAR
    INFILE unicode_var.dat "VAR 4"
    INTO TABLE STG_UNICODE
    TRUNCATE
    A CHAR(2) ,
    B CHAR(6) ,
    C CHAR(2) ,
    D CHAR(1) ,
    E CHAR(4)
    ) Datafile:
    001501NormalDExZWEI002702ÄÜÖßêÊûÛxöööö002604üuüüüüÖÄxµôÔµ Problems
    Implementing these two alternatives in OWB, I encounter the following problems:
    * How to specify LENGTH SEMANTICS CHAR?
    * How to suppress the POSITION definition?
    * How to define a flat file with variable length and how to specify the number of bytes containing the length definition?
    Or is there another way that can be implemented using OWB?
    Any help is appreciated!
    Thanks,
    Carsten.

    Hi Carsten
    If you need to support the LENGTH SEMANTICS CHAR clause in an external table then one option is to use the unbound external table and capture the access parameters manually. To create an unbound external table you can skip the selection of a base file in the external table wizard. Then when the external table is edited you will get an Access Parameters tab where you can define the parameters. In 11gR2 the File to Oracle external table can also add this clause via an option.
    Cheers
    David

  • How to compare table's date field with dropdown year field

    Hi All,
    I have one requirement to display the selected rows from a database table based on the selection of drop down.
    Here, I have one dropdown of year(like 2009,2010,....) and I have one database table which contains one field with "DATE".
    Now, I want to compare table's DATE field with my dropdown field.
    Problem is that table's DATE field is of type "DATS" and dropdown is of type INTEGER(or) STRING ...
    How to compare this fields?
    Can any one please give me solution for this...!
    Thanks in Advance!

    Hi  sreelakshmi.B,
    try the following:
    DATA lt_dats        TYPE TABLE OF dats.
    DATA l_dat_i        TYPE          i.
    DATA l_dat_c_4(4)   TYPE          c.
    DATA l_dat_c_12(12) TYPE          c.
    DATA l_dats_from    TYPE          dats.
    DATA l_dats_to      TYPE          dats.
    *Move Date from Integer to Char
    l_dat_c_4 = l_dat_i = 2005.
    *Create Date From use in WHERE-Clause
    CONCATENATE '01.01.' l_dat_c_4 INTO l_dat_c_12.
    CALL FUNCTION 'CONVERT_DATE_TO_INTERNAL'
         EXPORTING
              date_external            = l_dat_c_12
         IMPORTING
              date_internal            = l_dats_from
         EXCEPTIONS
              date_external_is_invalid = 1
              OTHERS                   = 2.
    IF sy-subrc <> 0.
    ENDIF.
    *Create Date To use in WHERE-Clause
    CONCATENATE '31.12.' l_dat_c_4 INTO l_dat_c_12.
    CALL FUNCTION 'CONVERT_DATE_TO_INTERNAL'
         EXPORTING
              date_external            = l_dat_c_12
         IMPORTING
              date_internal            = l_dats_to
         EXCEPTIONS
              date_external_is_invalid = 1
              OTHERS                   = 2.
    IF sy-subrc <> 0.
    ENDIF.
    * Select records in range
    SELECT *
           FROM [DBTAB]
           INTO TABLE [ITAB]
           WHERE [DATE] BETWEEN l_dats_from
                        AND     l_dats_to.
    Regards
    REA

  • How to implement the schema validation with XSD in adapter module

    Dear All,
    I am trying to develop a EJB as the file adapter mudule.
    Please guide me how to implement the schema validation of the source message with XSD.
    Or provide me the relative resources about this task.
    Thanks & Regards,
    Red
    Edited by: Grace Chien on Nov 19, 2008 8:23 AM

    Hi Grace,
    You can do the xml scema validation in PI7.1 version directly.
    To develop the adapter module for xml schema validation
    Validating messages in XI using XML Schema
    Schema Validation of Incoming Message
    Regards
    Goli Sridhar

  • How to create a date object with a specific time?

    How can I create a date with today's date but with a specific time, say: 20:00:00?
    Thanks in advance.

    Don't forget about those pesky milliseconds!I'd have gotten away with it too.. if it hadn't been
    for that pesky BigDaddyLoveHandles.I'm in top form today. On the drive in to work I managed to
    push two scooter riders off the road and gave the finger to
    a Prius owner.

  • Date validation with minValue on 1st February

    Here is my validation on a textfield which expect a date :
    var dateValidation = new
    Spry.Widget.ValidationTextField("dateValidation", "date",
    {isRequired:false, format:"dd/mm/yyyy", validateOn:["blur"],
    minValue:"31/01/2008", useCharacterMasking:true});
    Test with these parameters :
    Today date : 31/01/2008
    Try to enter 01/02/2008 and this date is detected as a date
    in the past.
    You can do the same with each year: try to put your today
    date on 31/01/2009 and enter 01/02/2009...
    Is it a bug from Spry?

    I debug the "SpryValidationTextField.js" and I found a bug in
    the date validation function.
    In javascript, when you create a new date, the month is on
    base "0".
    So when your month is January and the value typed is 1. If
    you would like to create a new date based on this month, you have
    to specified the month "0".
    Adobe Spry Team,
    could you correct the line :
    return (new Date(theYear, theMonth, theDay);
    by:
    return (new Date(theYear, theMonth - 1, theDay);

  • How to get old data back with original apple id

    HI Guys
    Wrongly i configured my iphone with some other apple id n nw all tat other user id data is been reflecting in my iphone, how shlud i gt my old data back with my original apple id. Rather whnevr i m connecting it with itunes tat odr user id is been reflecting........... how to slove dis issue pls guide.

    Hi Suyash,
    Check if this article is helpful in your case:
    https://www.sdn.sap.com/irj/servlet/prt/portal/prtroot/docs/library/uuid/f421c86c-0801-0010-e88c-a07ccdc69601
    /people/dinesh.lalchand/blog/2006/02/07/loopback-process--follow-up
    Regards
    Dinesh

  • How to read in date/time with ascii import

    I have an ascii data file with a time column in the following format
    ddd hh:nn:ss
    the seconds are like 11.1234567, so it would look like
    234 12:23:11.1234567
    I have tried different format options to read this in
    with no luck. The data I read in I am then using in CLIP/Insight. The video has this time on it and I need it in the data set to be able to sync them up.

    The problem with this data format seems to be the 'ddd' at the beginning of the data format.
    DIAdem expexts the 'dd' to be a day of a month, not a day in a year. I can offer you a solution though:
    Please upload or send me two of your data files and we will create a little script in DIAdem that will import your data format and make it available in DIAdem and DIAdem CLIP.
    You can upload them here in the forum or send them to me at:
    [email protected]
    Please compress the files (with ZIP or similar technology) if they are large.
    Otmar
    Otmar D. Foehner
    Business Development Manager
    DIAdem and Test Data Management
    National Instruments
    Austin, TX - USA
    "For an optimist the glass is half full, for a pessimist it's half empty, and for an engineer is twice bigger than necessary."

  • How to swap column-data along with Table header

    Hi All!
    I found a smple JTableDemo.java class. When I run it it provided sorting on the table as well as Dragging Column-data along with Table header while swaping two columns-headers.
    I designed my own table and apply some changes to TableModel. Afterwords it swaps Table-Headers only, but not their respective columns.
    Can someone give me a clue for that, where the logical error may be?
    Thanx in Advance

    surprised.. since you have asked, it must have some more tricky issue. Any way what i thought of it
    in before insert on table2
    simply insert into table1 (cr_id) values (:new.cr_id_id);
    i assume that table1 pk does not generated through sequence
    proposed insertion will not violate the uniqueness and create another record only in table1
    what is thehidden agenda for not using simple before insert trigger as above.
    yours
    dr.s.r.bhattachar

  • How do I put date along with time on my new iPad?

    I need to put date along with time on the top bar on my new I pad but just can't do it, need some help. Thank you in advance.

    Unless you can do it with a third party app - and I haven't seen one that will do it - you can't put the date at the top of the iPad. Those features are built into the iOS and there is no user setting to change or add anything to the time setting at the top.

  • Date validations for fiscal year

    My selection screen has select option for date in that it shold take financial year i.e from april to march.
    suppose if date-low = dec2008 date-high = feb2008. how shld i write the code for this.validations etc. it should not give error saying lower value is higher than high value.

    Hi,
    Anyhow you need to be careful with the validations of Fiscal year, i used the below code in one of my reports which gets Date and fiscal year as inputs;
    Data : fisYr1(4) TYPE n, fisyr2(4) TYPE n.
    CLEAR : fisyr1, fisyr2.
    IF S_date-low+4(2) LE 3.
      fisyr1 = s_date-low+(4) - 1.
    ELSE.
      fisyr1 = s_date-low+(4).
    ENDIF.
    IF S_date-high+4(2) LE 3.
      fisyr2 = s_date-high+(4) - 1.
    ELSE.
      fisyr2 = s_date-high+(4).
    ENDIF.
    IF fisyr1 NE fisyr2.
      invalid_date_Range = 'X'.
    ELSEIF fisyr1 NE p_fisyr.
      invalid_fiscal_year = 'X'.
    ENDIF.
    Regards
    Karthik D

Maybe you are looking for

  • Different ipods on same computer

    How do I set up two different itunes accounts on the same computer, one for my classic ipod and one for my son's ipod touch?

  • I changed my password for wifi connection and now my wifi won't connect.

    I have an Osprey mini. Last night I needed to connect a new device to the wifi but couldn't find the card with the network password, so I got to my account online and changed the password. But when I try to connect, it says the password is incorrect.

  • Powerpivot Workbook in Excel cannot be saved

    Hello All, There were some automatic updates done yesterday which made my Excel 2010 appearing in English today (instead of Swedish until yesterday), as well as making it unable to save Powerpivot workbooks (which is the part that concerns me!). When

  • Keynote will not open presentation which was edited 5 days ago in Keynote 6

    Anyone having this problem? Trying to open a presentation in Keynote 6.0 (1473). Double clicking the file provides the opening animation but no window appears with the presentation. I have also had two kernel panics due to this new Keynote but for th

  • Remote Restart of Services (with dependencies)

    Hello all, i've a short question about restarting a service on a remote machine with powerhell. I've tried the following: get-service -computername ServerXY -name ServiceXY | Set-Service -Status stopped And it works like a charm. But some services ha