Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 7 of 7

Thread: Help simplifying huge nested if statement?

  1. #1
    Junior Member
    Join Date
    Sep 2011
    Posts
    7
    My Mood
    Hungover
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Lightbulb Help simplifying huge nested if statement?

    This is a programming project from a textbook, and it executes as intended. However, I can't help but thinking there are ways to simplify the code because the if statement I am using is massive, with nested if statements inside.

    Any ideas on simplifying this code? Or any ideas on alternatives to the if statement I am using?

    (The program is to convert 24-hour time into 12-hour time, and the jpb package is needed to use the SimpleIO class.)

    // the jpb package needed to use the SimpleIO class
    import jpb.*;
     
    public class equivalent12HourTime
    {
    	public static void main(String[] args)
    	{
    		// hh:mm user input
    		SimpleIO.prompt("\nEnter a 24-hour time\n  in military hh:mm format\n   (example: 21:11 --> 11:11 p.m.) : ");
    		String hh_mm = SimpleIO.readLine();
     
    		// int hour
    		String hh = hh_mm.substring(0, 2);
    		int hour = Integer.parseInt(hh);
     
    		// int minutes
    		String mm = hh_mm.substring(3);
    		int minutes = Integer.parseInt(mm);
     
    		/* ginormous nested if statement:
    		   1. checks minutes for errors,
    		   2. checks hours for errors,
    		   3. converts 24-hour into 12-hour format and prints */
    		if ( (minutes <= 0) || (minutes >= 60) )
    		{
    			System.out.println("\nIncorrect time entered, please try again.");
    		}
    		else
    		{
    			if ( (hour > 0) && (hour <= 12) )
    			{
    				if (hour == 12)
    				{
    					System.out.println("\nEquivalent 12-hour time: " + hour + ":" + minutes + " p.m.");
    				}
    				else
    				{
    					System.out.println("\nEquivalent 12-hour time: " + hour + ":" + minutes + " a.m.");
    				}
    			}
    			else if ( (hour > 12) && (hour <= 24) )
    			{
    				if (hour == 24)
    				{
    					System.out.println("\nEquivalent 12-hour time: " + (hour - 12) + ":" + minutes + " a.m.");
    				}
    				else
    				{
    					System.out.println("\nEquivalent 12-hour time: " + (hour - 12) + ":" + minutes + " p.m.");
    				}
    			}
    			else
    			{
    				System.out.println("\nIncorrect time entered, please try again.");
    			}
    		} // end of if statement
    	}
    }


  2. #2
    Member
    Join Date
    Oct 2011
    Posts
    36
    Thanks
    0
    Thanked 2 Times in 2 Posts

    Default Re: Help simplifying huge nested if statement?

    In my opinion, there is no better solution than if statement in this situation.

  3. #3
    Crazy Cat Lady KevinWorkman's Avatar
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    5,162
    My Mood
    Hungover
    Thanks
    141
    Thanked 595 Times in 510 Posts

    Default Re: Help simplifying huge nested if statement?

    Yeah, that if statement doesn't seem that bad.

    You could try splitting it up into methods more though.

    But really, at the early stages of programming, don't worry about getting everything exactly correct. Does it work? Do you know how it works?
    Useful links: How to Ask Questions the Smart Way | Use Code Tags | Java Tutorials
    Static Void Games - Play indie games, learn from game tutorials and source code, upload your own games!

  4. The Following User Says Thank You to KevinWorkman For This Useful Post:

    racecar333 (October 31st, 2011)

  5. #4
    Junior Member
    Join Date
    Sep 2011
    Posts
    7
    My Mood
    Hungover
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: Help simplifying huge nested if statement?

    Hey thanks folks. Kevin -- what do you mean by splitting it up into methods more? Would this be to separate the information into categories for readability? (I'm thinking for the above code two separate methods for a.m. and p.m.?)

    and please reply to another question here if you have the time --
    How do I use the repaint method to "undraw"? (I am a noob)
    (I am having a lot of trouble with simple 2D animation right now)

  6. #5
    Crazy Cat Lady KevinWorkman's Avatar
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    5,162
    My Mood
    Hungover
    Thanks
    141
    Thanked 595 Times in 510 Posts

    Default Re: Help simplifying huge nested if statement?

    Quote Originally Posted by racecar333 View Post
    Hey thanks folks. Kevin -- what do you mean by splitting it up into methods more? Would this be to separate the information into categories for readability? (I'm thinking for the above code two separate methods for a.m. and p.m.?)
    If you have a bunch of nested if statements, like this:

    if(a){
       if(b){
          if(c){
             //something
          }
       }
    }
    else{
       if(d){
          if(e){
             //something else
          }
       }
    }

    You can make it more readable by doing something like this:

    if(a){
       doA();
    }
    else{
       if(d){
          if(e){
             //something else
          }
       }
    }
     
    public void doA(){
       if(b){
          if(c){
             //something
          }
       }
    )

    ..and obviously you could further break that down.
    Useful links: How to Ask Questions the Smart Way | Use Code Tags | Java Tutorials
    Static Void Games - Play indie games, learn from game tutorials and source code, upload your own games!

  7. #6
    Crazy Cat Lady KevinWorkman's Avatar
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    5,162
    My Mood
    Hungover
    Thanks
    141
    Thanked 595 Times in 510 Posts

    Default Re: Help simplifying huge nested if statement?

    Quote Originally Posted by racecar333 View Post
    and please reply to another question here if you have the time --
    How do I use the repaint method to "undraw"? (I am a noob)
    (I am having a lot of trouble with simple 2D animation right now)
    Copeg already gave you the correct answer, I'm not sure what else you want me to say about it.
    Useful links: How to Ask Questions the Smart Way | Use Code Tags | Java Tutorials
    Static Void Games - Play indie games, learn from game tutorials and source code, upload your own games!

  8. #7
    Forum VIP
    Join Date
    Oct 2010
    Posts
    275
    My Mood
    Cool
    Thanks
    32
    Thanked 54 Times in 47 Posts
    Blog Entries
    2

    Default Re: Help simplifying huge nested if statement?

    Glancing at your code, I would recommen d that rather than all of the parameter if statements, it would be better to have one method that simply checks the validity of the input, returning aboolean. Then end the program if the parameters aren't valid. EG:
    String hh_mm = SimpleIO.readLine();
    boolean isValid = checkValidity(hh_mm);
    if(!isValid)
    {
      System.err.println("Not a valid format");
      System.exit(1);
    }
    //Rest vof the code
    public static boolean checkValidity(String hh_mm)
    {
      if(some validity check)
      {
        return false;
      }
      if(some other validity check)
      {
         return false;
      }
      return true;
    }
    But, as Kevin said, it is best not to worry to much about getting it perfect as a begginer. I remember when I looked back at my old code (around when I swtarted) a few weeks ago. I practically died laughing

    @luck999 Nothing is perfect.
    Last edited by Tjstretch; November 1st, 2011 at 01:13 AM.

Similar Threads

  1. regarding nested queries in jsp
    By ravi_91 in forum What's Wrong With My Code?
    Replies: 1
    Last Post: June 4th, 2011, 10:15 AM
  2. Replies: 1
    Last Post: April 7th, 2011, 01:32 PM
  3. Streaming Raw Data to a Client - huge message loss
    By MarkusTandy in forum Java Networking
    Replies: 0
    Last Post: February 19th, 2011, 06:41 PM
  4. Nested If Else Statement
    By jwill22 in forum What's Wrong With My Code?
    Replies: 6
    Last Post: October 6th, 2010, 02:46 PM
  5. Nested try blocks
    By Ahmed. in forum Member Introductions
    Replies: 2
    Last Post: April 30th, 2010, 08:12 AM

Tags for this Thread