Results 1 to 2 of 2
  1. #1
    Nes_java is offline Member
    Join Date
    Apr 2011
    Posts
    5
    Rep Power
    0

    Cool help me rewrite my long code.

    The problem:
    Write a method named season that takes two integers as parameters representing a month and day and that returns a String indicating the season for that month and day. Assume that months are specified as an integer between 1 and 12 (1 for January, 2 for February, and so on) and that the day of the month is a number between 1 and 31.

    If the date falls between 12/16 and 3/15, you should return "Winter". If the date falls between 3/16 and 6/15, you should return "Spring". If the date falls between 6/16 and 9/15, you should return "Summer". And if the date falls between 9/16 and 12/15, you should return "Fall".

    And my code

    public static String season(int month, int day){
    String k="";
    if(month <3){
    k="Winter";
    }else if(month <6){
    k = "Spring";
    }else if (month <9){
    k = "Summer";
    }else if (month<12){
    k = "Fall";
    }
    if(month==3){
    if(day<=15){
    k="Winter";
    }else{
    k = "Spring";
    }
    }
    if(month==6){
    if(day<=15){
    k="Spring";
    }else{
    k = "Summer";
    }
    }
    if(month==9){
    if(day<=15){
    k="Summer";
    }else{
    k = "Fall";
    }
    }
    if(month==12){
    if(day<=15){
    k="Fall";
    }else{
    k = "Winter";
    }
    }
    return k;
    }
    My code is true, but I think it's quite long.
    Please help me rewrite my code to be shorter.
    thanks,

  2. #2
    sunde887's Avatar
    sunde887 is offline Moderator
    Join Date
    Jan 2011
    Location
    Richmond, Virginia
    Posts
    3,069
    Blog Entries
    3
    Rep Power
    8

    Default

    Instead of nested statements you can and together multiple conditions. With this you should be able to have four if clauses which each test some range, and if passed, returns the correct season string.

Similar Threads

  1. Please Review My Code (Long Integer Addition)
    By Saradus in forum New To Java
    Replies: 12
    Last Post: 07-05-2009, 01:01 PM
  2. Replies: 5
    Last Post: 05-25-2009, 09:03 PM
  3. Generate a random code 4 letters long
    By bl00dr3d in forum New To Java
    Replies: 9
    Last Post: 04-06-2009, 05:32 AM
  4. [SOLVED] url rewrite
    By mtyoung in forum Java Servlet
    Replies: 3
    Last Post: 02-02-2009, 10:12 AM
  5. rewrite mousedown code
    By brahms666 in forum New To Java
    Replies: 0
    Last Post: 11-26-2008, 01:15 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •