Data Validation/Filtering Using SmartView

Hi,
I just want to know that how can i apply Data Validation/filtering in SmartView.
For E.G if i want that Only those combination should be Shown where the Value of a Product is Always Greater than 2000.
Please help out
Thanks in Advance

Well, yes it is true you can write MDX for it but that isn't what you asked is it?
If you look at the Tech Ref
http://docs.oracle.com/cd/E17236_01/epm.1112/esb_tech_ref/frameset.htm?launch.html
and search for IIF there is an example there that should point you in the right direction.
WITH MEMBER
[Scenario].[Revised Budget]
AS
'IIF (
[Product].CurrentMember.Caffeinated,
Budget * 1.1, Budget
SELECT
{[Scenario].[Budget], [Scenario].[Revised Budget]}
ON COLUMNS,
[Product].Levels(0).Members
ON ROWS
FROM Sample.Basic
WHERE ([Measures].[Sales], [Year].[Qtr3])
Otherwise I might post a new question asking for someone to help you optimise an MDX query.
Steve

Similar Messages

  • Filtering data already filtered using DAX

    Hi there
    I am using DAX to calculate the count of instances in a filtered table
    e.g.
    =CALCULATE( COUNT(Table[Tariff] ,
    FILTER( Table , Table[Tariff] > 0 )
    This part of the code works fine. My trouble arises when I am trying to filter the table that I have already filtered:
    =CALCULATE( COUNT(Table[Tariff] ,
    FILTER ( FILTER( Table , Table[Tariff] > 0 ) , Table[Tariff] = MIN(Table[Tariff]) )
    In the above calculation, I want to 
    1. Filter out the tariffs that are greater than zero [this bit works fine]; and then
    2. Take that table filtered from 1. above and further filter that by extracting only those tariffs that are equal to the minimum in that data table [this part isn't working].
    Instead of doing what I need it to, this formula is treating the outer FILTER in the same manner that it would be treated if I had only one filter. Thus, as zero is the minimum in the unfiltered data set it is only returning all the zero tariffs - even through
    I filtered these out already.
    If anyone can please assist, it would be much appreciated.
    Cheers
    Andrew

    Hi Andrew,
    Something along these line may work...
    =CALCULATE(
    SUM(TariffData[Tariff])/COUNT(TariffData[Tariff]),
    FILTER(
    FILTER(
    TariffData,
    TariffData[BEGIN_DATE_INDEX] <= [Date_Count]
    && TariffData[END_DATE_INDEX] >= [Date_Count]
    TariffData[Tariff_Duration] = CALCULATE(
    MIN(TariffData[Tariff_Duration]),
    FILTER(
    TariffData,
    TariffData[BEGIN_DATE_INDEX] <= [Date_Count]
    && TariffData[END_DATE_INDEX] >= [Date_Count]
    ...But it's likely that you'll need to adjust the inner most CALCULATE to get the right behaviour due to the filter context transition. If you're able to provide some test data and details of how the data has been modelled, we should be able to arrive at
    a solution that definitely works.
    Regards,
    Michael Amadi
    Please use the 'Mark as answer' link to mark a post that answers your question. If you find a reply helpful, please remember to vote it as helpful :)
    Website: http://www.nimblelearn.com
    Blog: http://www.nimblelearn.com/blog
    Twitter: @nimblelearn

  • Table Data Validation, Created using ViewLink

    Hi All,
    I have two ViewObject SwitchFundFromVO and SwicthFundToVO, these two are linked with ViewLink. Now In the JSPX page i have two table. One is using SwitchFundFromVO and another one using SwitchFundToVO.
    Table: SwitchFundFromVO
    1.) This a pre populated table.
    2.) Its a single selection based row, whenever user clicked one row from this table, he/she can enter value at the SwicthFundToVO table below and can enter any number of rows.
    Use Case:
    So let say, if SwitchFundFromVO has 2 pre populated rows, and user select the first row to switch his fund from. then he goes to SwitchFundToVO table and enter 2 rows where he/she wants to switch the fund.
    And again user select the 2nd row from the SwitchFundFromVo and goes to SwitchFundToVO and enters two rows for this also.
    So now 1 rows of SwitchFundFromVO table is linked with 2 rows of SwitchFundToVO table.
    I have two columns in SwitchFundToVO, one is FundName and another is Percentage, now i want to check that those two rows user added for each of the SwitchFundFromVO should match with 100%. After user clicked Submit Button.
    Hope I am clear here, I am trying this with managed bean, but didnt get how to go about this kind of Validation.
    Thanks,
    Neeraj

    Thanks Arun,
    Will try as u suggested, but still i believe it wont calculate the percentage block by itself, we have to calculate percentage column and throw and error message if the sum is not equal to 100%.
    Anyways i will try and let you know.
    Thanks,
    Neeraj Halder

  • I am traveling out side of the U.S. and I am trying to up-date some apps on my iPod touch and now I'm getting this message... "Account Not In This Store Your account is NOT valid for use in the Ecuadorian store. You must switch to the U.S. store... help!

    I am traveling out side of the U.S. and I am trying to up-date some apps on my iPod touch. Now I'm getting this message... "Account Not In This Store. Your account is NOT valid for use in the Ecuadorian store. You must switch to the U.S. store"
    Please, is there anyone one out who can help me solve this problem? I just can seem to figure out how to get to the U.S. store... thanks!

    I just read this solution, tried it & now it's working...
    I think I found a fix...I went to Settings, iTunes & App Stores, then click on your Apple ID...view Apple ID...change country region to USA (even though it was already USA...just do it again...go through the steps making sure the United States store is selected...agree to the Terms of Service, THEN I think what the key is is to RE-auhorize your credit card...in my case all I had to do was enter the security code...and it worked...I am now able to download the YouTube app for example...couldn't do it before.

  • Data Validation in Excel used in Format Range

    Hi Experts,
    Im just wondering if there's a way i can use format range to carry out the data validation of excel.
    i mean, i need to limit the users to enter only numberic data to the input cells, hence they cannot input any letter and negative values.
    i tried applying the data validation in format range but, its not spreading the data validation.
    if i apply data validation to every cell, when i expand, the data validation disappears.
    Any advise.
    Thanks much as always...

    Hi,
    I was not able to use Data Validation in FORMAT RANGE.
    If you want to apply this data validation for the whole data range, you can apply this data validation in the first cell of the first row,first column of evdre. It will apply to the whole data range.
    If you want to apply this for certain columns, its a bit tricky.
    You must break your columnKeyRange into 2 and insert a column in between. In the 1st columnkeyrange, get the data, hide this column alone and add this column in getonlyrange. Next, in the newly inserted columns between the 2 column key ranges, you can use your Data Validation in 1st row. While expanding, it will automatically copy the data validation to the remaining rows. Now, In the second columnkeyrange, get the value based on the data validation cell, hide this column alone. So now you will have 3 columns, with those in the column key ranges as hidden ones and the one in between will be shown to the users.
    I know, this workaround is a bit tricky, but it works flawlessly. I have used this for umpteen sheets.
    Karthik AJ

  • Problem filtering using between dates

    Hi, I have a Measure in Webi that has to show the Invoicing Quantity between 2 dates. The thing is that i don't know how to do it and I tried many many times. The Dimension that has the date is a date field.
    The thing is that i tried to "check" if i'm mispelling something and I added the dates (start date and End DAte) as filters in the execution of the consult and it brings the data without any fail and also the correct quantities.
    How can I filter the invoicing quantities between 2 dates using a Measure?
    Thanks in advance,
    Reynaldo

    Hi Stratos, I have created a derived table in order to bring the Invoicing. The Dates aren't prompts fields, there are a Formula that if a launch the report today, it has to bring the invoices between monday and friday of last week, and also the sales of the last 21 days (that's the second column).
    The database is Oracle, I think the trouble is how the dates are shown by the DB, because are formated in DD/MM/YYYY HH:MM:SS and I need it only DD/MM/YYYY. I used the function To_date by oracle, but, still brings the HH:MM:SS, when I look for the values of the table.
    This problem, I think is going also to Webi and when I try to filter using a Measure doesn't bring data, but If I use the filter used by Webi (the one that modifies the query, brings the data ok)
    Can you help me?.
    Thanks in advance,
    PD: Hope you understand!
    Reynaldo

  • What is your strategy for form validation when using MVC pattern?

    This is more of a general discussion topic and will not necessarily have a correct answer. I'm using some of the Flex validator components in order to do form validation, but it seems I'm always coming back to the same issue, which is that in the world of Flex, validation needs to be put in the view components since in order to show error messages you need to set the source property of the validator to an instance of a view component. This again in my case seems to lead to me duplicating the code for setting up my Validators into several views. But, in terms of the MVC pattern, I always thought that data validation should happen in the model, since whether or not a piece of data is valid might be depending on business rules, which again should be stored in the model. Also, this way you'd only need to write the validation rules once for all fields that contain the same type of information in your application.
    So my question is, what strategies do you use when validating data and using an MVC framework? Do you create all the validators in the views and just duplicate the validator if the exact same rules are needed in some other view, or do you store the validators in the model and somehow reference them from the views, changing the source properties as needed? Or do you use some completely different strategy for validating forms and showing error messages to the user?

    Thanks for your answer, JoshBeall. Just to clarify, you would basically create a subclass of e.g. TextInput and add the validation rules to that? Then you'd use your subclass when you need a textinput with validation?
    Anyway, I ended up building sort of my own validation framework. Because the other issue I had with the standard validation was that it relies on inheritance instead of composition. Say I needed a TextInput to both check that it doesn't contain an empty string or just space characters, is between 4 and 100 characters long, and follows a certain pattern (e.g. allows only alphanumerical characters). With the Flex built in validators I would have to create a subclass or my own validator in order to meet all the requirements and if at some point I need another configuration (say just a length and pattern restriction) I would have to create another subclass which duplicates most of the rules, or I would have to build a lot of flags and conditional statements into that one subclass. With the framework I created I can just string together different rules using composition, and the filter classes themselves can be kept very simple since they only need to handle a single condition (check the string length for instance). E.g. below is the rule for my username:
    library["user_name"] = new EmptyStringFilter( new StringLengthFilter(4,255, new RegExpFilter(/^[a-z0-9\-@\._]+$/i) ) );
    <code>library</code> is a Dictionary that contains all my validation rules, and which resides in the model in a ValidationManager class. The framework calls a method <code>validate</code> on the stored filter references which goes through all the filters, the first filter to fail returns an error message and the validation fails:
    (library["user_name"] as IValidationFilter).validate("testuser");
    I only need to setup the rule once for each property I want to validate, regardless where in the app the validation needs to happen. The biggest plus of course that I can be sure the same rules are applied every time I need to validate e.g. a username.
    The second part of the framework basically relies on Chris Callendar's great ErrorTipManager class and a custom subclass of spark.components.Panel (in my case it seemed like the reasonable place to put the code needed, although perhaps extending Form would be even better). ErrorTipManager allows you to force open a error tooltip on a target component easily. The subclass I've created basically allows me to just extend the class whenever I need a form and pass in an array of inputs that I want to validate in the creationComplete handler:
    validatableInputs = [{source:productName, validateAs:"product_name"},
                         {source:unitWeight, validateAs:"unit_weight", dataField:"value"},
                   {source:unitsPerBox, validateAs:"units_per_box", dataField:"value"},
                        {source:producer, validateAs:"producer"}];
    The final step is to add a focusOut handler on the inputs that I want to validate if I want the validation to happen right away. The handler just calls a validateForm method, which in turn iterates through each of the inputs in the validatableInputs array, passing a reference of the input to a suitable validation rule in the model (a reference to the model has been injected into the view for this).
    Having written this down I could probably improve the View side of things a bit, remove the dependency on the Panel component and make the API easier (have the framework wire up more of the boilerplate like adding listeners etc). But for now the code does what it needs to.

  • Excise Invoice Cancellation on Date validation only

    Hi Experts,
    i am having critical requirement from Business, which is not available in SAP Standard, So i need help from you guys...
    Excise invoice can be cancelled on the same day of system/posting date. but when the system date and posting dates are not matching it should through error..
    Example  : i created Excise invoice on 17th june,2011 this is posting date of excise invoice, if i try to cancell on 17th june , it should allow.
                        but when i try to cancell the excise invoice on 18th june (system date) , it should not allow to cancell and it say Error !!!
    i heard there will be possible through User Exit  OR Function Module OR Routins ... Please help me
    Thanks and Regards
    Madhu

    Dear Madhusudhanan,
    Following are the list of User Exits available for J1IIN
    J_1I7_USEREXIT_EXCISE_BEF_SAVE User exit after the excise header and details are written and they can changed in J1IS  , J1IIN and Automatic creation of Excise Invoice.
    J_1I7_USEREXIT_EXINV_ADDL_DATA User exit for Excise Invoice Additional Data    in J1IS and J1IG                 
    J_1I7_USEREXIT_J1I5_MATFORM    User exit for J1I5 material form changes                           
    J_1I7_USEREXIT_J1I5_VALIDATE   User exit for subsequent J1I5 data validation                      
    J_1I7_USEREXIT_J1IEX_BEF_SAVE User exit for J1IEX before the data is saved                    
    J_1I7_USEREXIT_J1IEX_CHANGE    User exit for changing data before display             
    J_1I7_USEREXIT_J1IS_BASE_VALUE User exit to Change base value in J1IS                
    I strongly believe that the first exit will serve the purpose.
    Now if you are cancelling it using J1IH, Check the following thread.
    J1IH-User Exit
    Thanks & Regards,
    Hegal K Charles

  • Data Validation - a feature that Numbers really needs.

    Right now, the newly purchased Numbers app for iPad/iPhone is little more than a crippled document viewer for me because numbers doesn't support 'data validation' (as implemented in excel).
    Its not a hard concept and likely utilized in a LOT of spreadsheets on the planet.  Not supporting such a critical feature is a problem, as it makes numbers, at least for me, rather pointless as an authoring tool since I cannot change or update data in my worksheet without likely corrupting the document's data integrity.
    Hopefully, someone at Apple is working on fixing this.
    Given that one cannot use data validation - how do I lock down a spreadsheet so I don't accidentally change cell contents?
    The fact that there is no 'undo' button on the iPhone version that I do get on the iPad (same app) makes it worse.. I'm occasionally and unintentionally dragging selections of stuff around the page really hosing up the iPhone spreadsheet.
    So I need to just remember what needs to be updated, update the excel spreadsheet when I can, then delete the iWork-iCloud doc, upload the replacement, then refresh the iPhone/iPad version.. very cumbersome and not at all 'cloud-like' or usefull.
    Apple developers.. are you paying attention?

    Yeah I know that apple likely has the same system as Microsoft in sending general support to a forum such as this. And maybe thae same stupid moron that not paying attention to the forums if their users is a food idea.
    That doesn't change the point of the issue nor that apple directs ,e here to ask said question
    Written in the iPad split soft keypad that covers up the forum post I'm typing. Joy

  • Error While Inserting Data into table using OAF

    Hi Experts,
    I am learning OAF; i am trying into insert the data into table using OAF. I followed the below procedure.
    My table(OLF_TEST_TBL) Columns:
    EmpID (Number), Ename(VARCHAR2 100), Sal Number, and who columns.
    1. created Application Module (AM).
    package: oracle.apps.mfg.simplepg.server
    name: oaf_test_tbl_am
    2. created simple page
    name:EmployeePG
    package:oracle.apps.mfg.simplepg.webui
    3. Assigned the Application Module to Page
    4. Created Entity Object(EO)
    name:oaf_test_tbl_eo
    package:oracle.apps.mfg.simplepg.schema.server
    schema:apps
    table:OLF_TEST_TBL
    note:
    1. EMPID column is selected as primary key
    2. selected create method, remove method and validation method.
    3.checked generate default view object
    VO:
    name:olf_test_tbl_vo
    note: Entity Object was assigned to VO
    Coming To page:
    page main region:EmployeeMainRN
    1.under main region i created one more region using wizard
    selected AM and VO, region style-default single column
    2. under main region i created one more region
    region style- pagebuttonbar, ID:pagebutoonsRN
    3. under pagebuttonRN, created two submit buttons(ID:SUBMIT, ID:CANCEL).
    In AM java page:
    created a method to insert row and for commit.
    Insert Method:
    public void insertrow(){
    OAViewObject vo=(OAViewObject)getoaf_test_tbl_vo1();
    if(!vo.isPreparedForExecution()){
    vo.executeQuery();
    Row row=vo.createRow();
    vo.insertRow(row);
    row.setNewRowState(Row.STATUS_INITIALIZED);
    Commit Method:
    public void savaDataTooaftesttable(){
    getDBTransaction().commit();
    In EmployeeMainRN, created a controller.
    In this controller process request method, 'insertrow' method was called.
    import oracle.apps.fnd.framework.OAApplicationModule;
    public void processRequest(OAPageContext pageContext, OAWebBean webBean)
    super.processRequest(pageContext, webBean);
    if (!pageContext.isFormSubmission())
    OAApplicationModule am = pageContext.getApplicationModule(webBean);
    am.invokeMethod("insertrow");
    To commit the transaction when SUBMIT button pressed, commit method was called in process form request method.
    import oracle.apps.fnd.framework.OAViewObject;
    public void processformRequest(OAPageContext pageContext, OAWebBean webBean)
    super.processFormRequest(pageContext, webBean);
    OAApplicationModule am = pageContext.getApplicationModule(webBean);
    if (pageContext.getParameter("SUBMIT") != null)
    am.invokemethod("savaDataTooaftesttable");
    Error After clicking the submit button_
    I ran the page, page was opened successfully. Once i enter data and click submit button, it's giving the following error.
    The requested page contains stale data. This error could have been caused through the use of the browser's navigation buttons (the browser Back button, for example). If the browser's navigation buttons were not used, this error could have been caused by coding mistakes in application code. Please check Supporting the Browser Back Button developer guide - View Object Primary Key Comparison section to review the primary causes of this error and correct the coding mistakes.
    Cause:
    The view object oaf_test_tbl_am.oaf_test_tbl_vo1700_oaf_test_tbl_vo1_practice_test_prc1_oracle_apps_mfg_simplepg_server_oaf_test_tbl_am.oaf_test_tbl_vo1 contained no record. The displayed records may have been deleted, or the current record for the view object may not have been properly initialized.
    To proceed, please select the Home link at the top of the application page to return to the main menu. Then, access this page again using the application's navigation controls (menu, links, and so on) instead of using the browser's navigation controls like Back and Forward.
    Experts, Kindly help me why i am getting this error.
    Awating your replies.
    Thanks in advance.

    If you dont want to create message. You can throw exception like below as well
              throw new OAException("Emp Id is "+empId+" and employee name is "+empName, OAException.CONFIRMATION);Thanks
    --Anil                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

  • MDM Data Manager Assignments using Dates

    Hello.
    I am trying to create some assignments that default to a certain date and my expressions are getting the error message when I execute them.
    I am currently trying to create an Assignment for the Look-up table: Valid To (which belongs to the QT: Sales Data).
    I want the Valid To Assignment to default at the date 12/31/2999 if the user did not already enter a value.
    My expression looks like this:
    IF (IS_NULL(Sales Data.Valid To), SYSTIME(0) = 12/31/2999)
    I linked Sales Data for my 'Table Field'
    Any Ideas?
    Points awarded promptly for any help!
    Thanks,
    Nichole

    Hi,
    As per my knowledge, writing Assignments on Qualified Table field within the Main table is not possible for both Qualifier as well as Non-Qualifier Field. As if you want to write Assignment on Non-Qualifier fields only then you can do while selecting Qualified table as your Current Table not as Main table.
    For Qualifier field too if you want to asign field using Main table is not Possible as you cant select Property Table Field as Valid to here you could only able to select all Main table fields and fields which is look up to this Qualified table and other Sub tables.
    Don't confuse with other subtables.
    Other assignments that i've made work with just the 'sales data' table field even though there is a lookup table within that Q.T.
    That's why as you could get values for all other subtables in Assignment Expression as lookups tab if you remember like Reconcillation but here you could not find field who look up to your Qualified Table as well as Qualified table. there indirectly u r refering field to this lookup table and you get values here to assign but how could you assign value to Valid to field just think even if this is must requirement for you then you create one more subtable and look up this valid to field to this subtable or just create one more field  Valid to in maintable of type text.
    So from my point of view this is only drawback that we could not Assign Value to Qualified table field. I hope it will help you in understanding. But writing Validations for Qualified Table fields is Possible but not Assignments. May be in MDM 7.1 its possible. This is my knowledge about Writing Expressions for Qualified Table Fields till now. 
    Hope it will Help you,
    Rewards if found Useful.....
    Thanks,
    Mandeep Saini

  • Issue with data Validation while migrating from one application to another

    Hi All,
    I am having a strange issue Kindly please help me .
    I have a data form which have data validation on each cell.The dataform is quite large and contain data for 4 accounts and year (Jan to Dec) combination .The issue is that I when I migrate this data form to other application which is just the replica of the main application. The validation on each cells changes its reference points.
    I have 5 more similar data form and I need to migrate then to other application and also on production sever. Is there any way that while exporting and importing them using formutil.cmd or other way that the validation cells reference does not change its reference point.
    For ex I have validation on Cell A5,A6..........AA6 after migrating it changes to A1,A1.........AA1.
    I am using 11.1.2.1.0 version of Hyperion Planning
    Kindly please help.
    Thanks in advance
    Vikash
    Edited by: user11391767 on Nov 30, 2011 10:47 AM

    Hi Mehmet,
    I tried using the FormDefUtil.cmd .But by using this the reference points of validation changes to first cell when imported.
    Thanks
    Vikash

  • List data validation failed when creating a new list item but does not fail when editing an existing item

    Dear SharePoint Experts,
    Please help.
    Why does my simple formula work in Excel but not-work in SharePoint?
    Why does this formula...
    =IF([Request Type]="Review",(IF(ISBLANK([Request Date]),FALSE,TRUE)),TRUE)
    ...work in Excel but fail when I try to use it in SharePoint?
    The intent of this formula is the following...
    If the field "Request Type" has the value "Review" and the field "Request Data" is blank then show FALSE, otherwise show TRUE.
    SharePoint saves the formula, but when a list item is saved where the formula is implemented, (under List Settings, List Validation), SharePoint does not, say anything other than that the formula failed.
    Note that the "list data validation failed" error only happens when I am creating a new item-- the formula above works just fine when one is trying to Save on the edit form. 
    Can you help?
    Thanks.
    -- Mark Kamoski

    Dear Jason,
    I appreciate your efforts.
    However, it seems to me that this statement of yours is not correct...
    "If it meet the validation formula, then you can new or edit the item, otherwise, it will throw the 'list data validation failed' error, it is by design".
    I believe this is NOT the answer for the following reasons.
    When I create a new item and click Save, the validation error is "list data validation failed".
    When I edit an existing item and click Save, the validation error is "my custom error message" and this is, I believe, the way it needs to work each time.
    I think, at the core, the error my formula does not handle some condition of null or blank or other default value.
    I tried a forumla that casts the date back to a string, and then checked the string for a default value, but that did not work.
    I tried looking up the Correlation ID in the ULS when "list data validation failed" occurs, but that gave no useful information because, even though logging was set to Verbose, the stack trace in the error log was truncated and did not given any
    good details.
    However, it seems to me that SharePoint 2013 is not well-suited for complex validation rules, because...
    SharePoint 2013 list-level validation (NOT column-level validation) allows only 1 input for all the multi-field validation formulas in a given list-- so, if I had more than 1 multi-field validation rule to implement on a given list, it would need to be packed
    into that single-line-of-code forumla style, like Excel does. That is not practice to write, debug, or maintain.
    SharePoint 2013 list-level validation only allows 1 block of text for all such multi-field validation rules. So that will not work because I would have something like "Validation failed for one or more of the following reasons-- withdrawal cannot exceed
    available balance, date-of-birth cannot be after date-of-death,... etc". That will not work for me.
    The real and awesome solution would simply be enhancing SP 2013 so that column-level validation forumlas are able to reference other columns.
    But, for now, my workaround solution is to use JavaScript and jQuery, hook the onclick handler on the Save button, and that works good. The only problem, is that the jQuery validation rules run before any of the column-level rules created  with OOTB
    SP 2013. So, in some cases, there is an extra click for the enduser.
    Thanks,
    Mark Kamoski
    -- Mark Kamoski

  • Data validation for Date Field in Web Dynpro ABAP

    Hi ,
    In my WDA i want to perform data validation for date filed. (i.e. While creating a new record i have to check the Start Date should be always lesser than End Date.)
    If u ll enter the wrong date it should validate the Date and throw an error message.
    Please Reply soon its urgent.
    Thanks,
    Deepika

    Hi,
    First read the two attributes start date and end date.
    Then write the following condition.
    IF item_start_date > item_end_date.
    Error message.
    Endif.
    For pop up error message you need to use Create_window method of the Interface if_wd_window.
    Thanks.

  • 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

Maybe you are looking for