RU beehive logo ITEC dept promo banner
ITEC 120
2009spring
ibarland
nokie
jmdymacek

homeinfolectslabsexamshws
textbooktutor/PIsjava.lang docsjava.util docs

lect06a
introducing if-else

In lab we talked about how / can either mean floating point division, or quotient (or “integer division”), depending on context. [What is the rule, for which version you get?] We also saw that % gives the remainder, complementing integer-division.

Suppose we have a total number of minutes, and want to convert it to

class Song {
    
    String band;
    String title;
    int lengthSecs;  // The length of the song, in seconds.
                     // E.g., 131 means 2min,11sec long.

    // Constructor ...
 
    // getters and other methods, including:

    int getLengthSecs() {
        return this.lengthSecs;
        }
    

    // TO WRITE:
    // A method 'getLengthMMSS', which returns the length of the song
    // as a string like "2:11", suitable for humans to look at.

    // HINT: How would you approach this if we wanted to generate
    // the string "2min and 11sec" ?

        ... {
        int completeMins = this.lengthSecs / 60;
        int secsPastMinute = this.lengthSecs % 60;
        return ...
        }






    }

This version has a problem though: it doesn't pass the test case for a song of length 0 or 1 ! (Good thing we included such odd song-lengths in our test cases!) In fact, what are all the values of lengthSecs which cause a problem?

if-else

We can fix this by using a new Java statement: if-else. Here's how:

    String getLengthMMSS() {
        int completeMins = this.lengthSecs / 60;
        int secsPastMinute = this.lengthSecs % 60;
        if (secsPastMinute < 10) {
            return completeMins + ":0" + secsPastMinute;
            }
        else {
            return completeMins + ":" + secsPastMinute;
            }
        }
Note how we want to return different things in each case, so we do a (slightly different) return in the if branch, and in the else branch. Conceptually, the purpose of the entire if-else is to (always) return the correct answer.

Tip: Factoring out common code.
One slightly annoying thing about the above code is that the two return statements are nearly. We can avoid some of the repetition by taking the part that varies, and stick it in a variable. Then we'll only need to write the non-varying part (the number of minutes string-appended to the colon) once.

    String getLengthMMSS() {
        int completeMins = this.lengthSecs / 60;
        int secsPastMinute = this.lengthSecs % 60;

        String secsString;
        // Initialize secsString to be a two-digit string,
        // with leading zero as needed:
        if (secsPastMinute < 10) {
            secsString = ":0" + secsPastMinute;
            }
        else {
            secsString = "" + secsPastMinute;1
            }

        return completeMins + ":" + secsString;
        }
In this example, the purpose of entire the if-else statement is to initialize our variable. So really, we are still following our discipline of initializing our variable immediately after initializing it.

Sneaky: In fact, if you're looking closely, you might realize that we are still repeating the conversion of secsPastMinute into a String. By being clever, we can even get rid of that duplication: we realize that we are either sticking "0" inbetween the colon and the number of seconds, or we are sticking no-characters-at-all inbetween there. Hey, no-characters-at-all is the empty string.

    String getLengthMMSS() {
        int completeMins = this.lengthSecs / 60;
        int secsPastMinute = this.lengthSecs % 60;

        String secsPadding;
        if (secsPastMinute < 10) {
            secsPadding = "0";
            }
        else {
            secsPadding = "";
            }

        return completeMins + ":" + secsPadding + secsString;
        }
Notice how now, even the colon is only mentioned once. (And if we want to change it to some other character, we'll change only one place in our code, instead of two.)


1What a hack!, writing “""+” to get Java to convert-to-string for me. The appropriate (but long-winded) way would be to callInteger.toString(secsPastMinute). In languages besides Java, such explicit conversion might be required.      

homeinfolectslabsexamshws
textbooktutor/PIsjava.lang docsjava.util docs


©2009, Ian Barland, Radford University
Last modified 2009.Feb.27 (Fri)
Please mail any suggestions
(incl. typos, broken links)
to iba�rlandrad�ford.edu
Powered by PLT Scheme