Questions? Email

Join our weChat group or follow us on Facebook

©2019 by Legion of Learners

Oct 19

4.5 How to run part of code under certain conditions?


Edited: Oct 19

A. Introduction

In the example of writing a program to find the number of days in a month, we need to judge if a year is a leap year and if a month is a 30-day month or not. This can be done through branching using if... else...


B. First we need to read the data and set some variables:


Then we can decide based on the input:



  1. If there is only 1 statement in the block after either "if" or "else", { } is optional but we recommend to use { } always.

  2. When multiple if... else ... are nested, "else" is always matched to the nearest "if" regardless of indentation.

C. Try

R5.1-R5.5 on page 220 of chapter 5 of the Big Java Object

New Posts
  • sfolax6776
    7 days ago

    A. Introduction The third and last type of flow is all about repetitions: how to repeat some actions exact N times? or how to repeat some actions until certain status is achieved? There are actually three types of statements: for loops, while loops and do loops. B. Watch( Slides ) C. Try: Print out a multiplication table from 1 x 1 = 1 .... to 9 x 9 = 81. (Hint: you need a for loop inside a for loop)
  • sfolax6776
    Nov 1

    A. Introduction You were asked to use for-loops to print out a multiplication table, for-loops and nested for-loops are widely used for many applications. Here are some examples. B. Watch( Slides ) C. Try to print out the upper half or the lower half of a multiplication table like this:
  • sfolax6776
    Oct 26

    A. Introduction do loops are essentially same at while loops except that they will run at least once. All three types of loops can be converted into each other... Which one to choose? B. Watch( slides ) C. Try this: Write a do loop that reads integers and computes their sum. Stop when reading a zero or the same value twice in a row. For example, if the input is 1 2 3 4 4, then the sum is 14 and the loop stops.