Colorado State University Logo | CS 163/4: Java Programming (CS 1) Colorado State University Logo | CS 163/4: Java Programming (CS 1)
CS 163/4: Java Programming (CS 1)
Computer Science

Lab 04 - Branching

Introduction

In this lab, you will work on a simple program helps you learn about condition statements, both for primitives and for Strings. By the end you will have a very simple program that outputs a greeting, a person’s zodiac sign, and some information about their favorite number. This is also the first lab that has multiple files, and we will talk you through those files.

Review of Branching

Branching logic statements allow programmers to create multiple scenarios for their code to follow depending on different input criteria. The most basic of branching logic statements is the If statement.

The if statement is like asking a question, for example “Do you like mac and cheese?”, if yes make mac and cheese. On top of this you have the else statement, this statement is a form of default statement for a question. “Do you like mac and cheese?”, if yes make mac and cheese else make hamburgers. In programming, if statements are used to creating branching pathways that the code can take.

1
2
3
4
5
if (logical statement) {
    /*Code here*/
} else {
    /*Code here*/
}

The following conditional operators exist for primitive values (int, double, char).

  • == (Equals)
  • > (Greater than)
  • < (Less than)
  • >= (Greater than or equal)
  • <= (Less than or equal)

As Strings are objects, you have to use methods to compare than. Common methods are

  • equals (Strings are exactly equal including case)
  • equalsIgnoreCase (Strings are equal ignoring case)

Here are a couple reviews to look up if you need them:

For the links above, ignore the part about switch statements. We won’t cover that for a few more weeks.

Reviewing The Code

This is the first time you have dealt with multiple files in a lab. Java is made up of many files, classes, all interacting together. If you click the arrow by the file name, you will be able to see both files.

The details of the files are as follows:

  • BranchingMain.java
    This file contains your main method (public static void main(String[] args)), which also means it is an entry point into your program. Looking through this file, you will see a number of methods designed to help you test your code. It is very common practice that for every method you write, you write a secondary method to test it.
  • Branching.java
    This is the heart of your program logic. You will code all of the methods in this class, so let’s start here! Select the file Branching.java in the drop down.

One last thing before moving onto code - make to replace YOUR NAME, YOUR EMAIL with your name and email.

Part 1 .compareTwo(int first, int second)

compareTwo(int, int) compares two numbers together. Based on the values of the numbers it is going to return a String. At its heart, it is three if/else statements. The first if/else condition is done for you as an example:

1
2
3
4
5
if(first < second) { 
  output = output + first + " is less than " + second + "\n";
} else {
  output = output + first + " is not less than " + second + "\n";
}

A couple things to notice about the code, the return value of the method is output, and you are concatenating to it with every value. Given the newline character is added \n that means your String will contain multiple lines if it is printed (which it is in the test method).

Now it is your turn to write two additional statements.

  1. If the first integer is greater than or equal to second integer.
    • [first] is greater than or equal to [second]
      else
    • [first] is not greater than or equal to [second]
  2. If the first integer is equal to the second integer
    • [first] is equal to [two]
      else
    • [first] is not equal to [two]

For example:

System.out.println(compareTwo(0, 1));

Would output:

0 is less than 1
0 is not greater than or equal to 1
0 is not equal to 1

Work through the method, writing only a couple of lines at a time, running program, and more lines.

Testing compareTwo(int first, int second)

When you run the program, it will automatically test the method by calling compareTwoTests(). You should find that method in BranchingMain.java. You should add your own tests, as we only tested a limited set of numbers.

Part 2 numberGame(int number)

The numberGame repeats using if statements, but instead of setting a variable, you will notice the example uses returns.

1
2
3
if(number == 7) return "Lucky Sevens";
  //TODO Student    
return "Positive number";  

Once you return out of the method, the rest of the code isn’t processed. The following numbers to look for are in no particular order:

  • If the number is less than 10 but greater than 0, return “Single digit”.
  • If the number is 7 return “Lucky Sevens”.
  • If the number is 42, return “The answer to life the universe and everything”.
  • If the number is below 0, return “negative number”.
  • If the number is 0, return “ZERO”.
  • Otherwise return “Positive number”.

Hint: Your if statements should go from most specific to least specific. If one answer falls under another category then its statement should be returned, not the other category’s statement. For example if the number is 7, the method should return “Lucky Sevens” not “Single Digit”.

Testing numberGame(int number)

You should be testing as you write each line (really, typos are easy to type, but hard to find). Go to the numberGameTest(), and add tests. You will notice we did not test all the conditions, and you should.

Part 3 nameIntroductions(String first_name, String last_name)

For this next method you are going to practice if statements with strings. You will write a method called “nameIntroductions” that takes two strings, a first and last name, and returns a string containing a short message to the user.

We have completed the first half of the statements for you. However, the second half of the greating needs to be added to the message String.

If their last name is between 0 and 5 letters long the message ends “, I am sure glad to meet you!”.

If the last name is between 6 to 13 letters long the message ends “, I hope you are having a good day so far!”. Otherwise the message ends “ how are you doing this fine day!”.

Be careful about commas and spacing!

One last reminder, to get the length of the String, call .length() - for example:

1
int len = last_name.length();

Here are a couple examples of output from a successfuly working method.

What is up Audrey Dorin, I am sure glad to meet you!
Good day Matthew Ernst, I am sure glad to meet you!
What is up Isabella Zapata, I hope you are having a good day so far!

Testing nameIntroductions(String first_name, String last_name)

While we tested the names above in nameIntroductionsTests(), you will want to test other names.

Part 4 zodiacSign(String, int)

For this method you will be writing a Zodiac checking method. Based

If the user enters a day less than zero or greater than 31 return “Please enter a valid day”. If the user gives a month that does not exist return “Please enter a valid month”. Beyond that you should return Your Zodiac is [Zodiac Sign]!.

You can check this website for the dates associated with each zodiac sign. We will be using the Tropical Zodiac dates from the Date Table section.

  • Hint: You can place an if statement within another if statement, especially when attempting to compare multiple variables.
  • Hint: December and deCember are the same month regardless of capitalization. You may want to look at equalsIgnoreCase.
  • Hint: Draw it out! It is easy to get lost in if/else statements with this method.

Testing zodiacSign(String, int)

You should test after every zodiac sign, including adding your own tests to zodiacSignTests(). This method would become extremely hard if you don’t test after every sign. Work through the different scenarios.

Some example input and output is as follows:

1
2
3
System.out.println(Branching.zodiacSign("December", 17));
System.out.println(Branching.zodiacSign("February", 31)); // notice!
System.out.println(Branching.zodiacSign("April", 23));
Your Zodiac is Sagittarius!
Please enter a valid day
Your Zodiac is Taurus!

Step 5 playGame()

For the next part, you will get to play the built in game putting it all together. To play the game, type run game in the interactive terminal.

Go ahead and run the game a few times. You will notice the output doesn’t look correct when it is asking the questions. Fine the line of code with an error in it, and fix the error. This step is simply to remind you of the differences between print and println, and to give you experience reading other’s code.

Once you have completed this step, you should go into submit mode, and submit for grading.

Computer Science Department

279 Computer Science Building
1100 Centre Avenue
Fort Collins, CO 80523
Phone: (970) 491-5792
Fax: (970) 491-2466

CS 163/4: Java Programming (CS 1)

Computer Programming in Java: Topics include variables, assignment, expressions, operators, booleans, conditionals, characters and strings, control loops, arrays, objects and classes, file input/output, interfaces, recursion, inheritance, and sorting.