Programming Activities

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 41

JOSE RIZAL MEMORIAL STATE UNIVERSITY

COLLEGE OF ARTS AND SCIENCES


BS INFORMATION SYSTEMS DEPARTMENT
Main Campus |

Sta. Cruz, Dapitan City

COMPILATION OF
PROGRAMMING EXERCISES
CC 103 Data Structures and
Algorithms

Submitted by:
Family name, First name MI.
Family name, First name MI.
Family name, First name MI.
BS Information Systems
Submitted to:
Engr. Ryann Z. Elumba
Instructor

ACTIVITY 1
INSTALLING THE JDK

First, you need the Java Development Kit (JDK) from Oracle. This is the actual
compiler that your development environment (IDE) uses behind the scenes. Even if
you already have Java installed, you probably still need this. (Most people only have
the Java Runtime Environment (JRE) installed, which allows you to run existing Java
programs but not compile new ones.)
Direct your web browser to
http://www.oracle.com/technetwork/java/javase/downloads/
Click the big "Java Download" button above where it says "Java Platform (JDK) 8u111 /
8u112", or any newer version if it's newer.

Evaluation
1. What is the purpose of a JDK?
Replace this with your answer.
2. Document below the steps in installing the JDK in your computer (include
screenshots).

21

ACTIVITY 2
COMPILER CHECK
This activity is designed to make sure that the Java compiler (JDK) is correctly
installed on your machine.
1. Open a terminal window or command prompt.
C:\>javac version

2. You will see one of two things. If the JDK / Java compiler is correctly installed,
you should see a version number like so:
C:\>javac -version
javac 1.7.0_04

The exact version number doesn't matter, as long as it starts with "1.6" or
higher.
However, if the JDK isn't installed, then you'll see an error like so:
C:\>javac -version
'javac' is not recognized as an internal or external command,
operable program or batch file.

3. Once you've got the JDK installed, close the command prompt, open the
comment prompt again, and try once more:
C:\>javac -version
javac 1.7.0_04

Success!

Evaluation
1. Document below the steps in checking the compiler version of your JDK by
showing the screenshots of the steps above.

21

ACTIVITY 3
COMPILING PRACTICE
This activity is designed to give you practice compiling and running a Java program.
Start by encoding the following code in notepad. Save the code as SineWave.java in
the MyProgram folder in the drive D:.
import java.awt.*;
import java.awt.geom.*;
import javax.swing.*;
public class SineWave
{
public static void main ( String[] args )
{
SineFrame frame = new SineFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
/**
A frame with a message panel
*/
class SineFrame extends JFrame
{
public SineFrame()
{
setTitle("SineTest");
setSize(WIDTH,HEIGHT);
// add panel to frame
SinePanel panel = new SinePanel();
Container contentPane = getContentPane();
contentPane.add(panel);
}
public static final int WIDTH = 640;
public static final int HEIGHT = 480;
}
/**
A panel that shows a sine wave
*/
class SinePanel extends JPanel
{
public SinePanel()
{
w = 6;
old_x = 5;
old_y = 240;
analog = false;
}
public void paintComponent( Graphics g )
{
super.paintComponent(g);
Graphics2D g2 = (Graphics2D)g;
g2.draw(new Line2D.Double(0,240,640,240));
for ( x=5;x<635;x++)
{
y = 240 + 60*Math.sin((x-30)/45);
if ( ( analog || x%6==0 ) )
{
if ( analog )
{
if ( old_x <= x )
g2.draw(new
Line2D.Double(old_x,old_y,x,y));
old_x = x; old_y = y;
}

21

else
{
if ( y < 240 )
{
ul_y = y;
h = 240 - y;
}
else
{
ul_y = 240;
h = y - 240;
}
g2.draw(new
Rectangle2D.Double(x2,ul_y,w,h));
}
}
}
}
double x, y, old_x, old_y;
double ul_y;
double w, h;
boolean analog;
}

Then open up a command prompt.


Compile the program with the "javac" utility and then run the bytecode file through
the "java" interpreter to execute it, as shown below.
C:\>d:
D:\>cd MyProgram
D:\MyProgram>
D:\MyProgram>javac SineWave.java
D:\MyProgram>java SineWave.*

Evaluation
1. What is the function of a compiler?
Replace this with your answer.

21

ACTIVITY 4
AN IMPORTANT MESSAGE
This exercise will show you the detailed steps you must follow to create your first Java
program.
Launch Notepad. (Start Menu | All Programs | Accessories | Notepad)
Then, type in the code listed below. Save your file as "FirstProg.java".

Keep Notepad open; you will need it again if there are errors.
Open a command prompt. (Start Menu | All Programs | Accessories | Command
Prompt) Then type, in order, the commands below.
C:\>d:
D:\>cd MyProgram
D:\MyProgram>javac FirstProg.java

If the command appears to do nothing, then it's working correctly! If it gives errors,
though, then something is wrong. Look back at your code and fix any differences.
Once the compiling step (javac) completes with no errors, then your new program is
ready to run!
D:\MyProgram>java FirstProg
Mr. Mitchell is cool.

You did it! Now try changing the code so that the computer displays a different
message.

Evaluation
1. What are the different types of errors in Java? Explain each type of error.
Replace this with your answer.
2. Enumerate some rules in writing a code in Java.

21

ACTIVITY 5
A GOOD FIRST PROGRAM
Remember, you should have spent a good amount of time in the last assignment
learning how to install a text editor, run the text editor, run a command prompt, and
work with both of them. If you haven't done that then don't go on, you'll not have a
good time. This is the only time I'll start an exercise with a warning that you should
not skip or get ahead of yourself.
public class GoodFirstProgram
{
public static void main( String[] args )
{
System.out.println( "Hello World!" );
System.out.println( "Hello Again" );
System.out.println( "I like typing this." );
System.out.println( "This is fun." );
System.out.println( "Yay! Printing." );
System.out.println( "I'd much rather you 'not'." );
System.out.println( "I \"said\" do not touch this." );
}
}

Take the above and type in into a single file named GoodFirstProgram.java. This is
important as Java works best with files ending in .java.
Then, in a command prompt you compile the file by typing:
D:\MyProgram>javac GoodFirstProgram.java

If you did it right then nothing should happen. The computer will just skip a single
blank line and display a prompt again. If not, then you've done something wrong. No,
the computer is not wrong.
Then, assuming there were no errors, you should run the program by typing:
D:\MyProgram>java GoodFirstProgram

If you did it right then you should see the same output I have below. If not, then
you've done something wrong.
What You Should See
D:\MyProgram>java GoodFirstProgram
Hello World!
Hello Again
I like typing this.
This is fun.
Yay! Printing.
I'd much rather you 'not'.
I "said" do not touch this.

If your output is not exactly the same, then find out why and fix it. If you have an
error it will look like this:
D:\MyProgram>javac GoodFirstProgram.java
GoodFirstProgram.java:6: ';' expected
System.out.println( "Hello Again" ):
^
1 error

It's important you be able to read these since you'll be making many of these
mistakes. Even I make many of these mistakes. Let's look at this line-by-line.
1. Here

we

ran

our

command

GoodFirstProgram.java file.

in

the

terminal

to

compiler

the

2. The Java compiler then tells us that the file GoodFirstProgram.java has an error
on line 6. In this case, the specific error is that a semicolon was expected ( ';'
expected)
3. It then prints this line for us.

21

4. Then it puts a ^ (caret) character to point at where it thinks the problem is.
Notice that there is a colon (':') at the end of the line instead of a semicolon
(';')
5. Finally, it prints out the total number of errors.
Usually the specific error messages are very cryptic, but if you copy that text into a
search engine you'll find someone else who's had that error and you can probably
figure out how to fix it.

Evaluation
1. Put two slashes ('//') at the beginning of one of the println() statements. What
did it do?
Replace this with your answer.

Code
Modify the code above by adding 2 more lines of output.
Insert your code here

21

ACTIVITY 6
COMMENTS AND SLASHES
Comments are very important in your programs. They are used to tell you what
something does in English, and they also are used to disable parts of your program if
you need to remove them temporarily. Here's how you use comments in Java:
public class CommentsAndSlashes
{
public static void main( String[] args )
{
// A comment, this is so you can read your program later.
// Anything after the // is ignored by Java.
System.out.println( "I could have code like this." ); // and the
comment after is ignored.
// You can also use a comment to "disable" or comment out a piece
of code:
// System.out.println("This won't run.");
System.out.println( "This will run." );
}
}

From now on, I'm going to write code like this. It is important for you to understand
that everything does not have to be literal. Your screen and program may visually
look different, but what's important is the text you type into the file you're writing in
your text editor. In fact, I could work with any text editor and the results would be the
same.
What You Should See
I could have code like this.
This will run.

Code
Modify the code above by adding another comment with the names of your group
mates.
Insert your code here

21

ACTIVITY 7
A LETTER TO YOURSELF
Write a program that displays your name and address on the screen as if it were a
letter. Your output should look something like that below.
+------------------------------------------------------------+
|
#### |
|
#### |
|
#### |
|
|
|
|
Bill Gates
|
|
1 Microsoft Way |
|
Redmond, WA
|
|
|
+------------------------------------------------------------+

Frequently-Asked Questions
Does my letter have to look exactly like yours?
No, but it does have to look roughly like a letter, including the box around the outside
and the stamp.
Do I have to use my real address?
Of course not. But make sure your fake address takes up three lines.
How to I get a | to show up on the screen?
The | character is called a "pipe". Assuming you are using a normal US keyboard, it is
Shift + backslash (\). The backslash key is usually located between the Backspace
and Enter keys.

Code
Insert your code here

21

ACTIVITY 8
YOUR INITIALS
Display your initials on the screen in block letters as shown.
For the name Jorge Balderama Perez...
JJJJJ
J
J
J
J J
J J
JJ

BBBB
B
B
B
B
BBBB
B
B
B
B
BBBB

PPPP
P
P
P
P
PPPP
P
P
P

In case you have no idea how to make a certain letter, there are some suggestions
below.

Code
Insert your code here

21

ACTIVITY 9
NUMBERS AND MATH
Every programming language has some kind of way of doing numbers and math.
Don't worry, programmers lie frequently about being math geniuses when they really
aren't. If they were math geniuses, they would be doing math, not writing ads and
social network games to steal people's money.
This exercise has lots of math symbols so let's name them right away so you know
what they're called. As you type this one in, say the names. When saying them feels
boring you can stop saying them. Here are the names:
+ plus
- minus
/ slash
asterisk
% percent
< less-than
> greater-than
<= less-than-or-equal
>= greater-than-or-equal
Notice how the operations are missing? After you type in the code for this exercise
you are to go back and figure out what each of these does and complete the table.
For example, + does addition.
public class NumbersAndMath
{
public static void main( String[] args )
{
System.out.println( "I will now count my chickens:" );
System.out.println( "Hens " + ( 25 + 30 / 6 ) );
System.out.println( "Roosters " + ( 100 - 25 * 3 % 4 ) );
System.out.println( "Now I will count the eggs:" );
System.out.println( 3 + 2 + 1 - 5 + 4 % 2 - 1 / 4 + 6 );
System.out.println( "Is it true that 3 + 2 < 5 - 7?" );
System.out.println( 3 + 2 < 5 - 7 );
System.out.println( "What is 3 + 2? " + ( 3 + 2 ) );
System.out.println( "What is 5 - 7? " + ( 5 - 7 ) );
System.out.println( "Oh, that's why it's false." );
System.out.println( "How about some more." );
System.out.println( "Is it greater? " + ( 5 > -2 ) );
System.out.println( "Is it greater or equal? " + ( 5 >= -2 )
);
System.out.println( "Is it less or equal? " + ( 5 <= -2 ) );
}
}

What You Should See


I will now count my chickens:
Hens 30
Roosters 97
Now I will count the eggs:
7
Is it true that 3 + 2 < 5 - 7?
false
What is 3 + 2? 5
What is 5 - 7? -2
Oh, that's why it's false.
How about some more.
Is it greater? true
Is it greater or equal? true
Is it less or equal? false

21

What You Should Do on Your Own


Assignments turned in without these things will not receive any points.
1. Above each line, use two slashes // to write a comment to yourself explaining
what the line does.
2. Notice the math seems "wrong"? There are no fractions, only whole numbers.
Find out why by researching what a "floating point" number is.
3. Rewrite NumbersAndMath.java to use floating point numbers so it's more
accurate (hint: 20.0 is floating point).
Frequently-Asked Questions
Why is the % character called "modulus" instead of "percent"?
Mostly that's just how the designers of Java chose to use that symbol. In normal
writing you are correct to read it as a "percent", as in "100%" is "one hundred
percent". In programming this calculation is typically done with simple division and
the / operator. The % modulus is a different operation that just happens to use the %
symbol.
How does modulus (%) work?
Another way to say it is, "X divided by Y with J remaining." As in, "100 divided by 16
with 4 remaining." The result of % is the J part, or the remainder part.
What is the order of operations?
In the United States we use an acronym called PEMDAS which stands for Parentheses
Exponents Multiplication Division Addition Subtraction. That's the order Java follows
as well.
Why does / (divide) round down?
It's not really rounding down, it's just dropping the fractional part after the decimal.
Try doing 7.0 / 4.0 and compare it to 7 / 4 and you'll see the difference. The first way
uses "floating point division" and the second way uses "integer division".

Code
Insert your code here

21

ACTIVITY 10
VARIABLES AND NAMES
You can print things out with System.out.println and you can do math. The next step
is to learn about variables. In programming a variable is nothing more than a name
for something so you can use the name rather than the something as you code.
Programmers use these variable names to make their code read more like English,
and because programmers have a lousy ability to remember things. If they didn't use
good names for things in their software they'd get lost when they came back and
tried to read their code again.
If you get stuck with this exercise, remember the tricks you've been taught so far for
finding differences and focusing on details:
1. Write a comment above each line explaining to yourself what it does in
English.
2. Read your .java file backwards.
3. Read your .java file out loud, saying even the punctuation and symbols.
public class VariablesAndNames
{
public static void main( String[] args )
{
int cars, drivers, passengers, cars_not_driven, cars_driven;
double
space_in_a_car, carpool_capacity,
average_passengers_per_car;
cars = 100;
space_in_a_car = 4.0;
drivers = 30;
passengers = 90;
cars_not_driven = cars - drivers;
cars_driven = drivers;
carpool_capacity = cars_driven * space_in_a_car;
average_passengers_per_car = passengers / cars_driven;
System.out.println( "There are " + cars + " cars available." );
System.out.println( "There are only " + drivers + " drivers
available." );
System.out.println( "There will be " + cars_not_driven + "
empty cars today." );
System.out.println( "We can transport " + carpool_capacity + "
people today." );
System.out.println( "We have " + passengers + " to carpool
today." );
System.out.println( "We need to put about " +
average_passengers_per_car + " in each car." );
}
}

Note: The _ in space_in_a_car is called an underscore character. Find out how to type
it if you do not already know. We use this character a lot to put an imaginary space
between words in variable names.
What You Should See
D:\MyProgram>java VariablesAndNames
There are 100 cars available.
There are only 30 drivers available.
There will be 70 empty cars today.
We can transport 120.0 people today.
We have 90 to carpool today.
We need to put about 3.0 in each car.

What You Should Do on Your Own


Assignments turned in without these things will not receive any points.
1. I used 4.0 for space_in_a_car, but is that necessary? What happens if it's just
4?
2. Remember that 4.0 is a "floating point" number. Find out what that means.
3. Write comments above each of the variable assignments.

21

4. Make sure you know what = is called (equals) and that it's making names for
things.
5. Remember _ is an underscore character.
Frequently-Asked Questions
What is the difference between = (single-equal) and == (double-equal)?
The = (single-equal) assigns the value on the right to a variable on the left. The ==
(double-equal) tests if two things have the same value. You'll learn more about
comparing things in a later assignment.
What do you mean by "read the file backwards"?
Very simple. Imagine you have a file with 16 lines of code in it. Start at line 16, and
compare it to my file at line 16. Then do it again for 15, and so on until you've read
the whole file backwards.
Why did you use 4.0 for space_in_a_car? Changing it to 4 doesn't seem to do
anything.
That is because space_in_a_car was previously defined as a double variable. If it had
been defined as an int variable, putting 4 into it would have made a difference.

Code
Insert your code here

21

ACTIVITY 10
USING VARIABLES
Write a program that creates three variables: an int, a double, and a String.
Put the value 113 into the first variable, the value 2.71828 into the second, and the
value "Computer Science" into the third. It does not matter what you call the
variables... this time.
Then, display the values of these three variables on the screen, one per line.
This is room # 113
e is close to 2.71828
I am learning a bit about Computer Science

Your program SHOULD NOT look like this:


System.out.println( "This is room # 113" );
System.out.println( "e is close to 2.71828" );
System.out.println( "I am learning a bit about Computer Science" );

You must use three variables. Your program will probably have nine lines of code
inside the curly braces of main().

Code
Insert your code here

21

ACTIVITY 11
STILL USING VARIABLES
Write a program that stores your name and year of graduation into variables, and
displays their values on the screen.
Make sure that you use two variables, and that the variable that holds your name is
the best type for such a variable, and that the variable that holds the year is the best
type for that variable.
Also make sure that your variable names are good: the name of a variable should
always relate to its contents.
My name is Juan Valdez and I'll graduate in 2010.

Notice that in the example above, the values "Juan Valdez" and 2010 have been
stored in variables before printing.
You're doing it wrong if your program looks like this:
System.out.println(
2010." );

"My

name

is

Juan

Valdez

and

I'll

graduate

in

Code
Insert your code here

21

ACTIVTY 12
ASKING QUESTIONS
It's now time to pick up the pace a bit. I've got you doing a lot of printing so that you
get used to typing simple things, but those simple things are fairly boring. What we
want to do now is get you getting data into your programs. This though is a little
tricky so we have to have you learn to do two things that may not make sense right
away, but if you stick with it they should click suddenly a few exercises from now.
Most of what software does is the following:
1. Take some kind of input from a person.
2. Change it.
3. Print out something to show how it changed.
So far you've only been printing, but you haven't been able to get any input from a
person, or change it. You may not even know what "input" means, so rather than talk
about it, let's have you do some and see if you get it. Next exercise we'll do more to
explain it.
import java.util.Scanner;
public class AskingQuestions
{
public static void main( String[] args )
{
Scanner keyboard = new Scanner(System.in);
int age;
String height;
double weight;
System.out.print( "How old are you? " );
age = keyboard.nextInt();
System.out.print( "How tall are you? " );
height = keyboard.next();
System.out.print( "How much do you weigh? " );
weight = keyboard.nextDouble();
System.out.println( "So you're " + age + " old, " + height + "
tall and " + weight + " heavy." );
}
}

Notice that we used print instead of println. This is so that the program doesn't end
the line with a newline and go to the next line.
What You Should See
D:\MyProgram>java AskingQuestions
How old are you? 35
How tall are you? 6'2"
How much do you weigh? 180
So, you're 35 old, 6'2" tall and 180 heavy.

What You Should Do on Your Own


Assignments turned in without these things will not receive any points.
1. Change the program so that it reads in the height in two parts. The first part
should read in an int for the number of feet. Then read in a second int for the
number of inches. Try to make the output look the same, though.
How
How
And
How
So,

old are you? 35


many feet tall are you? 6
how many inches? 2
much do you weigh? 180
you're 35 old, 6'2" tall and 180 heavy.

21

Code
Insert your code here

21

ACTIVITY 13
NAME, AGE, AND SALARY
Ask the user for their name. Then display their name to prove that you can recall it.
Ask them for their age. Then display that. Finally, ask them for how much they make
and display that. You should use the most appropriate data type for each variable.
Hello.
Dennis

What is your name?

Hi, Dennis!
37

How old are you?

So you're 37, eh? That's not old at all!


How much do you make, Dennis?
8.50
8.5!

I hope that's per hour and not per year! LOL!

Code
Insert your code here

21

ACTIVITY 14
MORE USER INPUT OF DATA
Ask the user for several pieces of information, and display them on the screen
afterward as a summary.
first name
last name
grade (classification)
student id number
login name
GPA (0.0 to 4.0)
You must use the most appropriate type for each variable and not just Strings for
everything.
Please enter the following information so I can sell it for a profit!
First name: Helena
Last name: Bonham-Carter
Grade (9-12): 12
Student ID: 453916
Login: bonham_453916
GPA (0.0-4.0): 3.73
Your information:
Login: bonham_453916
ID:
453916
Name: Bonham-Carter, Helena
GPA:
3.73
Grade: 12

Code
Insert your code here

21

ACTIVITY 15
AGE IN FIVE YEARS
Ask the user for their name. Then display their name to prove that you can recall it.
Ask them for their age. Then display what their age would be five years from now.
Then display what their age would be five years ago.
Hello.

What is your name? Percy_Bysshe_Shelley

Hi, Percy_Bysshe_Shelley!

How old are you? 34

Did you know that in five years you will be 39 years old?
And five years ago you were 29! Imagine that!

Code
Insert your code here

21

ACTIVITY 16
A DUMB CALCULATOR
Make a simple numeric calculator. It should prompt the user for three numbers. Then
add the numbers together and divide by 2. Display the result. Your program must
support numbers with decimals and not just integers.
D:\MyProgram>java DumbCalculator
What is your first number? 1.1
What is your second number? 2.2
What is your third number? 5.5
( 1.1 + 2.2 + 5.5 ) / 2 is... 4.4

Code
Insert your code here

21

ACTIVITY 17
BMI CALCULATOR
The body mass index (BMI) is commonly used by health and nutrition professionals to
estimate human body fat in populations.
It is computed by taking the individual's weight (mass) in kilograms and dividing it by
the square of their height in meters.
Sample Output
Your height in m: 1.75
Your weight in kg: 73
Your BMI is 23.83673

Code
Insert your code here

21

ACTIVITY 18
WHAT IF
Here is the next Java program you'll enter, which introduces you to the if statement.
Type this in, make it run exactly right and then we'll see if your practice has paid off.
public class WhatIf
{
public static void main( String[] args )
{
int people = 20;
int cats = 30;
int dogs = 15;
if ( people < cats )
{
System.out.println( "Too many cats!

The world is

doomed!" );
}
if ( people > cats )
{
System.out.println( "Not many cats!
}

The world is saved!" );

if ( people < dogs )


{
System.out.println( "The world is drooled on!" );
}
if ( people > dogs )
{
System.out.println( "The world is dry!" );
}
dogs += 5;
if ( people >= dogs )
{
System.out.println( "People are greater than or equal to
dogs." );
}
if ( people <= dogs )
{
System.out.println( "People are less than or equal to dogs."
);
}
if ( people == dogs )
{
System.out.println( "People are dogs." );
}
}
}

What You Should See


D:\MyProgram>java WhatIf
Too many cats! The world is doomed!
The world is dry!
People are greater than equal to dogs.
People are less than equal to dogs.
People are dogs.

What You Should Do on Your Own


Assignments turned in without these things will receive half credit or less.
In this section, you're going to try to guess what you think the if statement is and
what it does.
1. What do you think the if does to the code under it? Put your answer in a
comment in the code.

21

2. What is the purpose of the curly braces in the if statement? Answer in a


comment.
3. Change the values of the variables so that neither message about cats is
printed.

Code
Insert your code here

21

ACTIVITY 19
HOW OLD ARE YOU?
Make a program which displays a different message depending on the age given.
Here are the possible responses:
age is less than 16, say "You can't drive."
age is less than 18, say "You can't vote."
age is less than 25, say "You can't rent a car."
age is 25 or over, say "You can do anything that's legal."
Here's a sample run. Notice that a person who is under 16 will display three
messages, one for being under 16, one for also being under 18, and one for also
being under 25.
Hey, what's your name? Billy_Corgan
Ok, Billy_Corgan, how old are you? 17
You can't vote, Billy_Corgan.
You can't rent a car, Billy_Corgan.

Code
Insert your code here

21

ACTIVITY 20
ELSE AND IF
Type this one in and make it work, too.
public class ElseAndIf
{
public static void main( String[] args )
{
int people = 30;
int cars = 40;
int buses = 15;
if ( cars > people )
{
System.out.println( "We should take the cars." );
}
else if ( cars < people )
{
System.out.println( "We should not take the cars." );
}
else
{
System.out.println( "We can't decide." );
}
if ( buses > cars )
{
System.out.println( "That's too many buses." );
}
else if ( buses < cars )
{
System.out.println( "Maybe we could take the
buses." );
}
else
{
System.out.println( "We still can't decide." );
}
if ( people > buses )
{
System.out.println( "All right, let's just take the
buses." );
}
else
{
System.out.println( "Fine, let's stay home then." );
}
}
}

What You Should See


D:\MyProgram>java ElseAndIf
We should take the cars.
Maybe we could take the buses.
All right, let's just take the buses.

What You Should Do on Your Own


Assignments turned in without these things will receive half credit or less.
In this section, you're going to try to guess what you think the if statement is and
what it does.
1. What do you think else if and else are doing? Answer in a comment.
2. Remove the else part at the beginning of one of the else if statements. What
difference does that make? Why? Answer in a comment.

21

Code
Insert your code here

21

ACTIVITY 21
SPACE BOXING
Julio Cesar Chavez Mark VII is an interplanetary space boxer,
championship belts for various weight categories on many
our solar system. However, it is often difficult for him to
weight" needs to be on earth in order to make the weight
Write a program to help him keep track of this.

who currently holds the


different planets within
recall what his "target
class on other planets.

It should ask him what his earth weight is, and to enter a number for the planet he
wants to fight on. It should then compute his weight on the destination planet based
on the table below:
#
1
2
3
4
5
6

Planet
Venus
Mars
Jupiter
Saturn
Uranus
Neptune

Relative gravity
0.78
0.39
2.65
1.17
1.05
1.23

So, for example, if Julio weighs 128 lbs. on earth, then he would weigh just under 50
lbs. on Mars, since Mars' gravity is 0.39 times earth's gravity. (128 * 0.39 is 49.92)
Please enter your current earth weight: 128
I have information for the following planets:
1. Venus
2. Mars
3. Jupiter
4. Saturn 5. Uranus 6. Neptune
Which planet are you visiting? 2
Your weight would be 49.92 pounds on that planet.

Code
Insert your code here

21

ACTIVITY 22
A LITTLE QUIZ
Write an interactive quiz with 10 questions. It should ask the user three multiplechoice or true/false questions about something. It must keep track of how many they
get wrong, and print out a "score" at the end.
Are you ready for a quiz?
Okay, here it comes!

Q1) What is the capital of Alaska?


1) Melbourne
2) Anchorage
3) Juneau
> 3
That's right!
Q2) Can you store the value "cat" in a variable of type int?
1) yes
2) no
> 1
Sorry, "cat" is a string. ints can only store numbers.
Q3) What is the result of 9+6/3?
1) 5
2) 11
3) 15/3
> 2
That's correct!
Overall, you got 2 out of 3 correct.
Thanks for playing!

Code
Insert your code here

21

ACTIVITY 23
GENDER GAME
Make a program which displays an appropriate name for a person, using a
combination of nested ifs and compound conditions. Ask the user for a gender, first
name, last name and age.
If the person is female and 20 or over, ask if she is married. If so, display "Mrs." in
front of her name. If not, display "Ms." in front of her name. If the female is under 20,
display her first and last name.
If the person is male and 20 or over, display "Mr." in front of his name. Otherwise,
display his first and last name.
Note that asking a person if they are married should only be done if they are female
and 20 or older, which means you will have a single if and else nested inside one of
your if statements.
Also, did you know that with an if statement (or else), the curly braces are optional
when there is only one statement inside?
Example 1:
What is your gender (M or F): F
First name: Kim
Last name: Kardashian
Age: 32
Are you married, Kim (y or n)? y
Then I shall call you Mrs. Kardashian.

Example 2:
What is your gender (M or F): F
First name: Marisa
Last name: Tomei
Age: 48
Are you married, Marisa (y or n)? n
Then I shall call you Ms. Tomei.

Code
Insert your code here

21

ACTIVITY 24
ENTER YOUR PIN
Type in the following code, and get it to compile. This assignment will help you learn
how to make a loop, so that you can repeat a section of code over and over again!
import java.util.Scanner;
public class EnterPIN
{
public static void main( String[] args )
{
Scanner keyboard = new Scanner(System.in);
int pin = 12345;
System.out.println("WELCOME TO THE BANK OF MITCHELL.");
System.out.print("ENTER YOUR PIN: ");
int entry = keyboard.nextInt();
while ( entry != pin )
{
System.out.println("\nINCORRECT PIN. TRY AGAIN.");
System.out.print("ENTER YOUR PIN: ");
entry = keyboard.nextInt();
}
System.out.println("\nPIN ACCEPTED. YOU NOW HAVE ACCESS TO
YOUR ACCOUNT.");
}
}

What You Should See


WELCOME TO THE BANK OF MITCHELL.
ENTER YOUR PIN: 90210
INCORRECT PIN. TRY AGAIN.
ENTER YOUR PIN: 11111
INCORRECT PIN. TRY AGAIN.
ENTER YOUR PIN: 12345
PIN ACCEPTED. YOU NOW HAVE ACCESS TO YOUR ACCOUNT.
Notice what happens when we type the correct PIN on the first try:
WELCOME TO THE BANK OF MITCHELL.
ENTER YOUR PIN: 12345
PIN ACCEPTED. YOU NOW HAVE ACCESS TO YOUR ACCOUNT.

What You Should Do on Your Own


Assignments turned in without these things will receive no credit.
1. How is a while loop similar to an if statement?
2. How is a while loop different from an if statement?
3. Inside the while loop, why isn't there an int in front of the line entry =
keyboard.nextInt()?
4. Delete the line entry = keyboard.nextInt(); from inside the while loop. What
happens? Why?
5. (Put the entry = keyboard.nextInt(); back before you turn in the assignment.)

Code
Insert your code here

21

ACTIVITY 25
PIN LOCKOUT
Type in the following code, and get it to compile.
import java.util.Scanner;
public class PinLockout
{
public static void main( String[] args )
{
Scanner keyboard = new Scanner(System.in);
int pin = 12345;
int tries = 0;
System.out.println("WELCOME TO THE BANK OF MITCHELL.");
System.out.print("ENTER YOUR PIN: ");
int entry = keyboard.nextInt();
tries++;
while ( entry != pin && tries < 3 )
{
System.out.println("\nINCORRECT PIN. TRY AGAIN.");
System.out.print("ENTER YOUR PIN: ");
entry = keyboard.nextInt();
tries++;
}
if ( entry == pin )
System.out.println("\nPIN ACCEPTED. YOU NOW HAVE
ACCESS TO YOUR ACCOUNT.");
else if ( tries >= 3 )
System.out.println("\nYOU HAVE RUN OUT OF TRIES.
ACCOUNT LOCKED.");
}
}

What You Should See


WELCOME TO THE BANK OF MITCHELL.
ENTER YOUR PIN: 10101
INCORRECT PIN. TRY AGAIN.
ENTER YOUR PIN: 23232
INCORRECT PIN. TRY AGAIN.
ENTER YOUR PIN: 99999
YOU HAVE RUN OUT OF TRIES. ACCOUNT LOCKED.

What You Should Do on Your Own


Assignments turned in without these things will receive no credit.
1. Change the code so that it locks them out after 4 tries instead of 3. Make sure
to change the message at the bottom, too.
2. Move the "maximum tries" value into a variable, and use that variable
everywhere instead of just the number.

Code
Insert your code here

21

ACTIVITY 26
COUNTING WITH A WHILE LOOP
Type in the following code, and get it to compile. This assignment shows you how we
can abuse a while loop to make something repeat an exact number of times.
import java.util.Scanner;
public class CountingWhile
{
public static void main( String[] args )
{
Scanner keyboard = new Scanner(System.in);
System.out.println( "Type in a message, and I'll display it
five times." );
System.out.print( "Message: " );
String message = keyboard.nextLine();
int n = 0;
while ( n < 5 )
{
System.out.println( (n+1) + ". " + message );
n++;
}
}
}

Normally, while loops are best for repeating as long as something is true:
Keep going as long as they haven't guessed it.
Keep going as long as you haven't got doubles.
Keep going as long as they keep typing in a negative number.
Keep going as long as they haven't typed in a zero.
But sometimes, we know in advance how many times we want to do something.
Do this ten times.
Do this five times.
Pick a random number, and do it that many times.
Take this list of items, and do it one time for each item in the list.
We can do that sort of thing with a while loop, but we have to use a counter. A
counter is a number variable (int or double) that starts with a value of 0, and then we
add 1 to it whenever something happens. So, here, we're going to be adding 1 to the
counter everytime we repeat the loop. And when the counter reaches a
predetermined value, we'll stop looping.
What You Should See
Type in a message, and I'll display it five times.
Message: All work and no play makes Jack a dull boy.
1. All work and no play makes Jack a dull boy.
2. All work and no play makes Jack a dull boy.
3. All work and no play makes Jack a dull boy.
4. All work and no play makes Jack a dull boy.
5. All work and no play makes Jack a dull boy.

What You Should Do on Your Own


Assignments turned in without these things will receive no credit.
1. What does n++ do? Remove it and see what happens. (Then put it back.)
2. Change the code so that the loop repeats ten times instead of five.
3. See if you can change the code so that the message still prints ten times, but
the numbers in front count by tens, like so:
Type in a message, and I'll display it ten times.
Message: I'm sending out an S.O.S.
10. I'm sending out an S.O.S.
20. I'm sending out an S.O.S.

21

30. I'm sending out an S.O.S.


40. I'm sending out an S.O.S.
50. I'm sending out an S.O.S.
60. I'm sending out an S.O.S.
70. I'm sending out an S.O.S.
80. I'm sending out an S.O.S.
90. I'm sending out an S.O.S.
100. I'm sending out an S.O.S.

4. Change the code so that it asks the person how many times to display the
message. Then, print it that many times. Still count by tens.
Type in a message,
Message: HELLO! My
prepare to die.
How many times? 3
10. HELLO! My name
to die.
20. HELLO! My name
to die.
30. HELLO! My name
to die.

and I'll display it several times.


name is Inigo Montoya. You killed my father;
is Inigo Montoya. You killed my father; prepare
is Inigo Montoya. You killed my father; prepare
is Inigo Montoya. You killed my father; prepare

Code
Insert your code here

21

ACTIVITY 27
ADDING VALUES IN A LOOP
Write a program that gets several integers from the user. Sum up all the integers
they give you. Stop looping when they enter a 0. Display the total at the end.
You must use a while loop.
I will add up the numbers you give me.
Number: 6
The total so far is 6
Number: 9
The total so far is 15
Number: -3
The total so far is 12
Number: 2
The total so far is 14
Number: 0
The total is 14.

Code
Insert your code here

21

ACTIVITY 28
FLIP AGAIN?
In this program, you'll see how using a do-while loop might be better than a while
loop.
import java.util.Random;
import java.util.Scanner;
public class FlipAgain
{
public static void main( String[] args )
{
Scanner keyboard = new Scanner(System.in);
Random rng = new Random();
String again;
while ( again.equals("y") )
{
int flip = rng.nextInt(2);
String coin;
if ( flip == 1 )
coin = "HEADS";
else
coin = "TAILS";
System.out.println( "You flip a coin and it is... " +
coin );
System.out.print( "Would you like to flip again
(y/n)? " );
again = keyboard.next();
}
}
}

What You Should See


The code I have provided does not compile. Once you fix it, it will look roughly like
this.
You flip a coin and it
Would you like to flip
You flip a coin and it
Would you like to flip
You flip a coin and it
Would you like to flip

is...
again
is...
again
is...
again

TAILS
(y/n)? y
HEADS
(y/n)? y
HEADS
(y/n)? n

What You Should Do on Your Own


Assignments turned in without these things will receive no credit.
1. The code as given does not compile. Notice that the while loop tests if
again.equals("y"), but the variable again doesn't have a value at first. Give it a
value so that the code will compile and the loop will run at least once.
2. Now that program is working, change the loop from a while loop to a do-while
loop. Make sure it still works.
3. What happens if you delete what you added in step 1? Change the line back
to just String again; Does the program still work? Why or why not? (Answer in
a comment.)

Code
Insert your code here

21

ACTIVITY 29
RIGHT TRIANGLE CHECKER
Write a program to allow the user to enter three integers. You must use do-while or
while loops to enforce that these integers are in ascending order, though duplicate
numbers are allowed.
Tell the user whether or not these integers would represent the sides of a right
triangle.
Example 1:
Enter three integers:
Side 1: 4
Side 2: 3
3 is smaller than 4. Try again.
Side 2: -9
-9 is smaller than 4. Try again.
Side 2: 5
Side 3: 1
1 is smaller than 5. Try again.
Side 3: 5
Your three sides are 4 5 5
NO! These sides do not make a right triangle!

Example 2:
Enter three integers:
Side 1: 6
Side 2: 8
Side 3: 10
Your three sides are 6 8 10
These sides *do* make a right triangle.

Yippy-skippy!

Code
Insert your code here

21

ACTIVITY 30
TEN TIMES
Write a program that prints the important phrase "Mr. Mitchell is cool." on the screen
ten times. Use a for loop to do it.
Mr.
Mr.
Mr.
Mr.
Mr.
Mr.
Mr.
Mr.
Mr.
Mr.

Mitchell
Mitchell
Mitchell
Mitchell
Mitchell
Mitchell
Mitchell
Mitchell
Mitchell
Mitchell

is
is
is
is
is
is
is
is
is
is

cool.
cool.
cool.
cool.
cool.
cool.
cool.
cool.
cool.
cool.

If you want, you can number the lines of output like so:
1. Mr. Mitchell is cool.
2. Mr. Mitchell is cool.
3. Mr. Mitchell is cool.
4. Mr. Mitchell is cool.
5. Mr. Mitchell is cool.
6. Mr. Mitchell is cool.
7. Mr. Mitchell is cool.
8. Mr. Mitchell is cool.
9. Mr. Mitchell is cool.
10. Mr. Mitchell is cool.

Code
Insert your code here

21

ACTIVITY 31
NOTICING EVEN NUMBERS
Write a program that uses a for loop to display all the numbers from 1 to 20, marking
those which are even (divisible by two). It should use modulus by 2: if the remainder
is zero, it's divisible by 2.
This means you'll need an if statement inside the loop.
for ( <stuff> )
{
if ( <something with modulus> )
{
System.out.println( <something> );
}
else
{
System.out.println( <something different> );
}
}
1
2 <
3
4 <
5
6 <
7
8 <
9
10 <
11
12 <
13
14 <
15
16 <
17
18 <
19
20 <

Code
Insert your code here

21

You might also like