Expressions and
Flow Control
Objectives
Upon
completion of this lab, you should be able to:
- Use a simple for loop
- Using conditional statements in business logic
- (Optional) Use nested loops to implement a string search operation
Exercise
1:Using Loops and Branching Statements
In this
exercise, you will use a simple integer loop and branching statements
to play a fictitious game of foo
bar baz.
Create a
program that loops from 1-50 and prints each value on a separate line.
Also print foo for every
multiple or three, bar for
every multiple of lfive, and baz for
every multiple of seven. For example:
Code 4.1 (Partial) Output From FooBarBaz
Program
1
2
3 foo
4
5 bar
6 foo
7 baz
8
9 foo
10 bar
11
12 foo
13
14 baz
15 foo bar
16
and so on.
Preparation
Before you
begin, make sure that you have changed directories to exercises/mod04_stmts/exercise1/ using the cd
command in the terminal windows.
cd
~/exercises/mod04_stmts/exercise1/
Task
1 - Creating the FooBarBaz
Program
Using a text
editor, create a FooBarBaz program thet does the following:
- Declare
the FooBarBaz class.
- Declare
the main method.
- Use a for
loop to iterate from 1-50.
- a.
Print the current number.
- b.
Use three if statements to test if the current number is
divisible
by three, five, or seven; if so, print foo,
bar, and baz as
necessary.
Task 2 -
Compiling the FooBarBaz
Program
On the command
line, use the javac command to compile the best program.
Task 3 -
Running the FooBarBaz Program
On the command
line, use the java command to run the best program.
The output should look similar to Code 4-1 on page Lab 4-2.
Hints
These hints
might help you to solve this exercise:
- Use the System.out.print
method to print a string or value without printing a new line
character. You can use multiple print
methods to print a single line of text. You can use a single println method, with no arguments,
to print a new line character.
- The % operator calculates an integer remainder.
Exercise 2: Using Conditional Statements in the Account Class (Level
1,
Level 2, Level
3)