Lab4. Selection 1

advertisement
Name ___________________________
SFDV1003
Programming 1
Laboratory Workbook
Table of Contents
Introduction ........................................................................................................................................................................ 3
Lab1. Working with Dr Java ............................................................................................................................................ 6
Lab2. Class Structure ...................................................................................................................................................... 11
Lab3. Expressions ........................................................................................................................................................... 15
Lab4. Selection 1 ............................................................................................................................................................ 19
Lab5. Selection 2 ............................................................................................................................................................ 23
Lab6. Repetition 1 .......................................................................................................................................................... 27
Lab7. Repetition 2 .......................................................................................................................................................... 31
Lab8. Arrays ................................................................................................................................................................... 34
Lab9. Methods ................................................................................................................................................................ 40
Introduction
Welcome
Welcome to the laboratory sessions for SFDV1003. Programming is a very practical
skill. The best way to learn is to sit down and write programs. This means that the
laboratory sessions are probably the central part of SFDV1003 and the place that you
will really learn the art and craft of computer programming. We hope you find the
laboratory sessions useful and enjoyable.
About the Laboratory Sessions and Assessment
The Laboratory Workbook (Lab Book)
This book details the practical work for the laboratory sessions per week required for SFDV1003. (Each laboratory
session is two hours long). You need to bring this lab book with you to each session as it makes up part of the work
which is marked.
Work Load
You will find the laboratory time too short to complete the lab work unless you have done some preparation
beforehand.
SFDV1003 is an eighteen point paper. This means that during semester you should expect to spend roughly 8 hours
per week working on SFDV1003. This includes the 4 scheduled hours (2 hours of lectures and 2 hours of laboratories).
In other words you have 4 hours per week for your own work on understanding the concepts and preparation for the
laboratory sessions. This lab book contains background information and preparation exercises that are designed to be
read and done before each actual laboratory session. It also describes programming exercises to be done during the lab
session itself, although you need to think about them before you sit down in front of the computer.
Planning is such an essential part of programming that the demonstrators are not going to help you with your code for
some of the labs unless you have had a plan signed off. Demonstrators may also refuse to help you if you haven't
completed your preparation exercises, as these are specifically designed to build the knowledge required for your lab
work.
The course material builds quickly on itself. Consequently, it is important that you complete the work for one lab
session before going on to the next. Some of you may have some programming experience and might feel that the
programming problems are too easy. In this case please try other programming exercises from the text book, or you can
work on your own programming projects.
This is a fast moving course – if problems arise it is very important that you ask for help before you fall too far behind.
Don’t be afraid to ask – we are here to help.
Demonstrators
The demonstrators are there to help you understand the work and help you with any problems. They should give help,
especially if you have been stuck for a long time, but they are not there to simply tell you everything or to write the
programs for you! They will try to help you work out your own answers to the exercises and develop your own
understanding. Demonstrating is very difficult work and finding the right balance in answering a question is hard. The
process is sometimes frustrating for both them and you, so please be patient and understand the reasons for the amount
or kind of help that a demonstrator might give.
However, if you have any problems or comments concerning a demonstrator please feel free to contact the Course
Coordinator, your Class Representative or the Head of the Department. All communications will be dealt with
confidentially.
Working together
Many students find it helpful to work in small groups, and this cooperation is to be encouraged – you can learn a lot
from each other! Feel free to work on the Preparation questions together (this doesn’t mean copying someone else’s
answers, it means taking an active part in producing the answer). We expect you to work through the in-lab exercise
sheet with a partner.
Shared Work
When you present code for marking, it is very important that all of the code is written by you. It does not help you to
learn if you simply plagiarise (copy) a written answer or program. In order to pass SFDV1003 you must pass the final
exam, so gaining your own understanding is essential.
 Do not copy any portion of another student’s code.
 Do not lend, send or show your code to any other student. Copying requires two willing persons, the giver and
the taker. If another student copies your code, you will lose your marks as well.
 Do not assume that changing the variable names and comments makes the copying undetectable.
Several previous students can tell you this is not the case.
If you are falling behind and feeling stressed by the pace of the course, copying someone else’s code is not the best
solution.
If (when) you are caught plagiarising the matter will be dealt with severely under the Regulations. We routinely check
your code against that of your fellow students, and previous students. In order that we may be able to do this, we get
you to deliver a copy of your .java files as you get your labs marked. The demonstrators will show you how to do this
when it is required.
This course has clear policy with regard to copying the work of others:
Students should make sure that all submitted work is their own. Plagiarism
is a form of dishonest practice. Plagiarism is defined as copying or
paraphrasing another's work, whether intentionally or otherwise, and
presenting it as one's own (approved University Council, December 2004).
In practice this means plagiarism includes any attempt in any piece of
submitted work (e.g. an assignment or test) to present as one's own work the
work of another (whether of another student or a published authority). Any
student found responsible for plagiarism in any piece of work submitted for
assessment shall be subject to the dishonest practice regulations which may
result in various penalties, including forfeiture of marks for the piece of
work submitted, a zero grade for the paper, or in extreme cases exclusion
from the course.
Access to Java Programming Environments
DrJava is available for both Windows and Mac computers.
DrJava is also available as a free download, for Windows or Macintosh, from http://www.drjava.org should
you wish to install it on another computer.
Lab1.
Working with Dr Java
A journey of a thousand miles starts with a single step.
 Lao Tzu, Tao Te Ching
The reading for this lab is Chapter 1 of Lewis & Loftus (the text book). Chapter 1 is very general, and Labs 1 & 2
focus
on introducing DrJava (the application that we will use to write Java programs). On page 39, Lewis & Loftus describe
an Integrated Development Environment (IDE).
DrJava is a simple IDE which can be used on many different kinds of computer, including Macs, Windows, Linux and
other forms of Unix, to develop programs that run on many different kinds of computer. Java programs can also run on
many other kinds of device including some cell phones, PlayStations, Palm handhelds, and others. We will use DrJava
to write and run Java programs on Windows Operating System.
Preparation
Preparation questions are (mostly) taken from Lewis & Loftus (L&L) as indicated, and you will need to read L&L to
answer them. The questions below should be completed before you come to the lab session. Write your answers in the
space provided.
1. Exercise EX 1.15 (L&L p. 53). Give examples of the two types of Java comments and explain the differences
between them.
2.
Exercise EX 1.16 (L&L p. 53). Which of the following are not valid Java identifiers? Why?
Identifier
Valid?
a. Factorial

b. anExtremelyLongIdentifier

c. 2ndLevel

d. level2

e. MAX_SIZE

f. highest$

g. hook&ladder

Reason
3. What is the name of the method where statement execution begins in a Java application?
4. In Lab1, you called the method println without having to write a definition for it. How is this possible?
Lab Work
In this lab, we introduce DrJava (the application that we will use to write Java programs).
Part 1
DrJava is the application in which you will write and run your Java code. It is an Integrated Development Environment
(IDE) providing a graphical user interface (GUI) and tools for developing your computer programs. The IDE allows you
to edit, navigate, compile and run your code. You will soon be very familiar with this environment.
5. The physical process required for writing and running a java program involves four steps:
1) Typing in the code. DrJava will display a large window on the right hand side, underneath the DrJava tool
bar (Figure 1-1). This is the text editing window into which you will type your code.
Figure 1-1 The DrJava text editing window
Into the text editing window, type in the code for the HelloApp class listed below.
/*
* Hello World exercise.
DrJava will put a space after
* Lab 1 Part 1
the star - you will need to
* (your name) July 2007
*/
remove it
public class HelloApp{
public static void main (String[] args){
System.out.println("Hello world!");
}
}
2) Saving your file (class). Select File>
Save as and the Save window will appear.
Double-click on the
SFDV1003
directory that you created earlier.
Create a new directory for Lab 1 by
selecting New Folder (Figure 1-2). Name
your new folder Lab1.
Figure 1-2
Save your file in the Lab1 folder with the
name HelloApp.java (Figure 1-3).
F
igure 1-3
3) Compiling your code. Click on the
Compile All button on the toolbar (or the shortcut F5 key).
When you see "Last compilation completed successfully" in the lower window, a class file has been created
called HelloApp.class. If you see an error message in this window, check your code for typing errors,
correct your code, and save again (File> Save). Note: Java is case sensitive.
4) Running your program. Run your program using the Run button, or if your version of DrJava doesn't have
one, use the Tools> Run document's main method (or the shortcut F2 key).
You should see the output of the program in the lower window.
Part 2
1. Open a new DrJava file. Type in the following code:
/*
* TwoNumbersApp.java
* Lab 1 Part 2
* (your name) July 2007
*/
public class TwoNumbersApp{
public static void main (String[] args){
double num1;
double num2;
num1 = 8.0;
num2 = 15.0;
double sum = num1 + num2;
System.out.println("First number is " + num1);
System.out.println("Second number is " + num2);
System.out.println("Sum is " + sum);
}
}
2. Save the file in your Lab1 directory as TwoNumbersApp.java. Compile your code. The console window will come
up. If there are errors in your code, you will see them now. If you typed carefully, you will again see the message
"Last compilation completed successfully". When you alter code, you need to compile the changes before you run
it again, or the changes won’t have been made to the class file.
The sign you have known in mathematics as equals (=) needs in Java to be thought of as "gets the value"
or "is assigned the value". It is known as the assignment operator.
The statement num1 = 8.0; assigns the value 8.0 to the variable num1. The order is important!
The value on the right of the assignment operator is assigned to the variable on its left.
3. Run your program. Again the program output will appear in the lower window.
4. Add lines to your code to calculate and display the product of num1 and num2.
5. Save, compile and run your code.
Lab Completed
in-lab exercises complete
 relevant names used
Date
preparation exercises complete working
comments
parameter (printVerse)
Demonstrator's Initials
Lab2.
Class Structure
Notes
Readings: Chapter 2, Sections 2.1, 2.2, 2.6 (pp 60 - 71, 86 - 90).
You may feel that we have thrown you in at the deep end, but don't panic. Every concept introduced will be revisited in
its own time. For now, we ask you to look for patterns in the code examples you are given in lectures, in the text and in
this lab book. The lab work can be done by following the patterns. We don't expect you to understand it all at this stage.
You will need to look carefully at the code examples from your Lecture 3 notes in order to answer some of the
preparation questions.
Preparation
1. Exercise EX 2.4 (p. 104). What output is produced by the following statement? Explain.
System.out.println("50 plus 25 is " + 50 + 25);
2. Write a single code statement which will create the output below. Hint: Use an escape sequence.
A Poem by
Dr Seuss
3. a. The class Rhyme below defines two methods. Underline the two method headers. What are their names?
b. The class Rhyme below has two local variables. What are they called?
c. The main method in the class Rhyme below contains two method calls. Number them in order of execution.
d. Draw an arrow to the input parameter in the displayMessage method header.
public class Rhyme{
public static void main(String [] args){
String violets = "Violets are Blue";
String roses = "Roses are Red";
displayMessage(roses);
displayMessage(violets);
}// end main
/* method which displays whatever is stored in a String input parameter on
the screen*/
public static void displayMessage(String message){
System.out.println(message);
}//end displayMessage
}//end class
e. What will the output of this code be?
4. a. This code contains four method calls. There are two calls of the println method. Circle the other two method
calls.
public class Rhyme2{
public static void main(String [] args){
System.out.println(roses());
System.out.println(violets());
}//end main
/* method which returns a String to the point where it was called*/
public static String violets(){
return "Violets are Blue";
}//end violets
/* method which returns a String to the point where it was called*/
public static String roses(){
return "Roses are Red";
}//end roses
}//end class
b. What will the output of this code be?
5. Exercise EX 1.20 (L&L p. 54). Categorise each of the following situations as a compile-time error, run-time error, or
logical error.
a. multiplying two numbers when you meant to add them
b. dividing by zero
c. forgetting a semicolon at the end of a programming statement
d. spelling a word wrong in the output
e. producing inaccurate results
f. typing a { when you should have typed (
Lab Work
Part 1
1. Copy the following class to DrJava. Take a look at the code.
/*
* Lab
*/
2, SFDV1003
public class Fish{
public static void main(String [] args){
printVerse1();
}//end main
/*method displays verse 1 on the screen*/
public static void printVerse1(){
System.out.println("One fish\nTwo fish\nRed fish\nBlue fish.");
}//end printVerse1
}//end class
2. Compile and run. It should produce the output:
One fish
Two fish
Red fish
Blue fish.
3. Write another method in the class Fish which prints out verse 2 of the Dr Seuss poem shown below.
4. Compile your code. If you run your code now, you will see no change because you haven't called this new method
yet.
5. Call your new method from the main method, in order to produce an output like:
One fish
Two fish
Red fish
Blue fish.
Black fish
Blue fish
Old fish
New fish.
Part 2
1. Enter, compile, and run the following application:
public class Test{
public static void main (String[] args){
System.out.println("An Emergency Broadcast");
}
}
2. Introduce the following errors, one at a time, to the Test class. Record any error messages that the compiler
produces. Fix the previous error each time before you introduce a new one. If no error messages are produced,
explain why.
a. change Test to test
b. change Emergency to emergency
c. remove the first quotation mark
d. remove the second quotation mark
e. change main to man
f. change println to bogus
g. remove the semicolon at the end of the println statement
h. remove the last brace in the program
3. Fix the errors in the following code of the class Ex4App until it produces a correct output.
/*
* Lab 2 SFDV1003 – Ex4App.java
*/
public class Ex4{
public static Void mane(String [ args) {
System.Out.println( "There were eight errors." );
System.out.println( "Have you fixed the all? )
}
Lab Completed
in-lab exercises complete
lab tasks complete
Date
preparation exercises complete
comments
Demonstrator's Initials
Lab3.
Expressions
Notes
Readings: Chapter 2, Sections 2.4 - 2.6 (pp 75 - 90).
This lab will give you practical experience in writing mathematical expressions in Java. The readings cover all the
information you will need on operators, precedence and data conversion.
Preparation
1. Adapted from Exercise EX 2.6 (p. 104). What is printed out after each of the System.out.println statements
are executed?
int size = 18;
System.out.println(size);
________
size = size + 12;
System.out.println(size);
________
size = size * 2;
System.out.println(size);
________
size = size / 4;
System.out.println(size);
________
2. Exercise EX 2.8 (p. 105). What value is contained in the integer variable length after each of the following
statements are executed?
int length = 5;
length *= 2;
length *= length;
length /= 100;
________
________
________
________
3. Exercise EX 2.10 (p. 105). Given the following declarations, what result is stored in each of the listed assignment
statements?
Remember: If both operands are integers the result will be an integer. If this result is then stored as a double or
a float (as in b. below), it will be automatically widened.
int iResult, num1 = 25, num2 = 40, num3 = 17, num4 = 5;
double fResult, val1 = 17.0;
a.
iResult = num1 / num4;
g.
iResult = num1 / num2;
b.
fResult = num1 / num4;
n.
iResult = num3 % num4;
c.
iResult = num3 / num4;
o.
iResult = num2 % num3;
d.
fResult = num3 / num4;
p.
iResult = num3 % num2;
e.
fResult = val1 / num4;
q.
iResult = num2 % num4;
4. Exercise EX 2.11 (p. 106). For each of the following expressions, indicate the order in which the operators will be
evaluated by writing a number beneath each operator.
a.
a-b-c-d
h.
a - (b - c) - d
b.
a-b+c-d
i.
(a - (b - c)) - d
c.
a+b/c/d
j.
a - ((b - c) - d)
d.
a+b/c*d
m.
f.
a%b/c*d
(a + b) * c + d * e
5. Exercise EX 2.9 (L&L p. 105). Write four different program statements that increment the value of an integer variable
total by 1.
i)
ii)
iii)
iv)
Remember : The sign you have known in mathematics as equals (=) needs in Java to be thought of as
"gets the value" or "is assigned the value". It is known as the assignment operator.
The statement double num1 = 8.0; declares a real (rather than whole) number variable called
num1 which gets/is assigned the value 8.0. The order is important! The value on the right of the
assignment operator is assigned to the variable on its left.
Lab Work
Part 1
Create an application which reads a Fahrenheit value from the user and converts it to Celsius. The Fahrenheit
input value will need to be read as a double rather than an int.
You may like to work your way through to the reverse formula in the space below. Try to isolate celsius (C)
on one side of the equation. Maintain equality by performing equal operations on both sides. Call a
demonstrator if you need a hand.
F = C(9/5) + 32
CONVERSION_FACTOR + BASE)
(or F = C *
C=
Remember (Prep exercise 3) when converting a mathematical
expression to a Java expression that an int divided by
an int will produce an int, losing the fractional portion.
In the main method, write the code required to get input from the user, perform the calculation, and produce the output
display.
Use your program to fill in the following table:
Fahrenheit
32
98.6
212
Celsius
Part 2
1. Write an application that calculate the area of a CIRCLE and prints it out on the screen. In the main method,
write the code required to get input from the user, perform the calculation, and produce the output display.
2. Write an application that calculate the area of a RECTANGLE and prints it out on the screen. In the main
method, write the code required to get input from the user, perform the calculation, and produce the output
display.
Lab Completed
in-lab exercises complete
 Part1 average
Date
preparation exercises complete comments
Part2 celsius
submitted
Demonstrator's Initials
Lab4.
Selection 1
Notes
Readings: Chapter 5, Sections 5.1 - 5.4 (pp 210 - 234).
Selection is a fundamental part of all programming languages - we need to be able to select what to do next. Searching
and sorting problems crop up a lot in programming and are often used to illustrate selection. There are lots of efficient
sorting algorithms for different situations. The sorting method we use in this lab is called "Bubble Sort" (because the
smallest values "bubble" to the top). You will meet sorting again in Lab 18.
Preparation
1. Calculate the result of each expression if a is 5, b is 9, c is 14, and flag is true.
a. a == ( b + a – b)
b. ( c == ( a + b ) ) || ! flag
c. ( a != 7 ) && ( c >= 6) || flag
d. ! ( b <= 12 ) && ( a % 2 == 0 )
e. ! ( ( a > 5 ) || ( c < ( a + b ) ) )
2. Given:
char ch = 'f', digit = '8';
String aString = "comp";
What does each of the following evaluate to?
a. 'a' <= ch && ch <= 'z'
b. 'a' <= ch && 'z' <= ch
c. 'a' <= ch && 'z' >= ch
d. digit > '0' || digit < '8'
e. aString.equals("comp")
f. "comp".equals(aString)
g. aString.compareTo("zoom")
3. Exercise EX 5.3 (p. 280). What is wrong with the following code fragment? Will this code compile if it is part of an
otherwise valid program? Explain.
if (length = MIN_LENGTH)
System.out.println("The length is minimal.");
4. Write a boolean expression for each of the following:
a. ch is a lowercase letter
b. year is divisible by 4
c. waterLevel is less than 3.5 and greater than 2.9
d. height is greater than or equal to 1.5
e. ch is not a letter
f. score is from 25 to 40, inclusive
g. stringOne has the same value as stringTwo
5. Write a boolean expression to assign a value of true to child if age is in the range 0 to 17, inclusive;
otherwise assign a value of false.
6. Write a boolean expression to assign a value of true to pass if score is in the range 50 to 100, inclusive;
otherwise assign a value of false.
7. Write a boolean expression to assign a value of false to valid if score is less than 0 or greater than 100;
otherwise assign a value of true.
Three values
Initial
state
Final state
first
7
first = 4
second
6
second = 6
third
4
third = 7
swap values of first and second
Lab Work
Part 1
Your task is to three integer values, sort them into numerical order then print them out in order and in reverse order.
Sorting is a tricky problem. It can be solved in many ways, but some of the most obvious ones (based on repeatedly
comparing every number with every other number) are clumsy, and get worse as you have more things to sort. Some
solutions would need parts of Java that we haven't covered yet, but with what we know so far a fairly neat solution is
possible.
One way to sort the three numbers first, second and third is to break the task down into sorting "adjacent"
values: compare first and second (and swap their values if necessary), then compare second and third (and
swap their values if necessary), then compare first and second (and swap their values if necessary).
No matter what order the values start in, that will sort them. Try it out - show your working below on the example that
has been started for you.
Here is a segment of code that implements one of the adjacent sorts required.
if (second < first) {
// if second is smaller than first then we need to swap the
values
temp = first;
first = second;
second = temp;
// these three statements do the swap
}// if
Using these ideas, write a program that reads and sorts three integers. You should use a design with both an application
and a support class. Test your program on a variety of input orders. Is it hard to extend to sorting 4 elements? 5?
10?
Part 2
Write an application that calculates the solutions for the quadratic equation: ( ax2+bx+c=0 ) and prints them out on the
screen. In the main method, write the code required to get input from the user (a, b, and c), perform the calculation, and
produce the output display.
Lab Completed
in-lab exercises complete
private support methods
Date
preparation exercises complete
working
Demonstrator's Initials
comments
submitted
Lab5.
Selection 2
Notes
Readings: Chapter 5, Sections 5.1 - 5.4 (pp 210 - 234).
In this lab we work with the if else structure, and the switch statement.
Preparation
1. Exercise EX 5.2 (p. 280). What is wrong with the following code fragment? Rewrite it so that it produces correct
output.
if (total == MAX)
if (total < sum)
System.out.println("total == MAX and < sum.");
else
System.out.println ("total is not equal to MAX");
2. Exercise EX 5.5 (p. 281). What output is produced by the following code fragment?
int limit = 100, num1 = 15, num2 = 40;
if (limit <= limit){
if (num1 == num2)
System.out.println("lemon");
System.out.println("lime");
}
System.out.println("grape");
3. Write a switch statement that corresponds to the following:
if ((grade >= ‘A’ ) && (grade <= ‘C’ ))
System.out.println("Pass");
else if (grade == ‘D’ )
System.out.println("Fail");
else if ((grade == ‘E’ ) || (grade == ‘F’ ))
System.out.println("No credit");
else
System.out.println("Invalid grade");
Lab Work
Part 1
Programming Project PP 5.1 (p. 284). Design and implement an application that reads an integer value representing a
year from the user. The purpose of the program is to determine if the year is a leap year (and therefore has 29 days in
February) in the Gregorian calender. A year is a leap year if it is divisible by 4, unless it is also divisible by 100 but not
by 400.
For example, the year 2003 is not a leap year, but 2004 is. The year 1900 is not a leap year because it is divisible by 100
but not by 400. The year 2000 is a leap year because it is divisible by 100 and also divisible by 400. Produce an error
message for any input value less than 1582 (the year the Gregorian calender was adopted). This information is
summarised in Table 12-1.
The application should display the result to the console window, as
below
Enter a year: 2000
The year 2000 is a leap year.
/4
/100
/400
Leap
2003
no
no
no
no
2004
yes
no
no
yes
1900
yes
yes
no
no
2000
yes
yes
yes
yes
Table 12-1
Part 2
Write an application that prompts the user to enter an integer and checks whether the number is
divisible by both 5 and 6, neither, or just one of them. Here are some
sample outputs for inputs 10, 30, and 23:
10 is divisible by 5 or 6, but not both
30 is divisible by both 5 and 6
23 is not divisible by either 5 or 6
Lab Completed
in-lab exercises complete
Year
Date
preparation exercises complete
Family (comments changed)
Demonstrator's Initials
comments
submitted
Lab6.
Repetition 1
Notes
Readings: Chapter 5, Sections 5.5-5.7 (pp 234 - 252).
Much of the power of computing lies in the ability to repeat tasks a certain number of times, or until a particular state
has been reached, or until the end of the job. Loops are the key to repetition, and there are a number of different loops
which may be used. In this lab we will look at the while and the do-while loops.
Preparation
1. The do-while loop below is combined with a switch statement to create a simple menu. Add a statement to call
a method playGame() if the user chooses 1. Add another statement to print out a farewell message if the user
chooses 0.
do {
System.out.println("\n\n What is your choice,\n" +
" 1 to play the game\n" +
" 0 to quit");
choice = readInt("Enter your choice");
// returns an int read from the console
switch (choice){
// select the case indicated by
choice
case 1: {
break;
}// case1
case 0: {
break;
}// case2
}// switch
} while (choice != 0);
2. Exercise EX 5.7 (p. 281). What output is produced by the following code fragment?
int num = 0, max = 20;
while (num < max){
System.out.println(num);
num += 4;
}
3. Exercise EX 5.8 (p. 282). What output is produced by the following code fragment?
int num = 1, max = 20;
while (num < max){
if (num % 2 == 0)
System.out.println(num);
num ++;
}
4. Exercise EX 5.11 (p. 282). Transform the following while loop into an equivalent do loop (make sure it produces
the same output).
int num = 1;
while (num < 20){
num++;
System.out.println(num);
}
5. Write a while loop that displays each integer from 14 to 25 (inclusive). Include any necessary declarations.
6. What is the minimum number of times a while loop is executed?
7. What is the minimum number of times a do-while loop is executed?
Problem: Play a guessing game with the computer. It chooses a number between 1 and 100 (inclusive), and the
user has to guess that number. The computer will tell the user if the guess was right, too high or too low. The
game continues until the user guesses the correct value, after which the user is told how many guesses they
made.
Algorithm:
1 generate a random number between 1 and 100 (inclusive)
2 get a guess from the user
3 increase the guess counter by 1
4 if the guess is too high, print out "Too high" or else if the guess is too low, print out "Too low"
repeat steps 2,3 and 4 until guess equals random number
5 print out "Correct, you took x guesses"
Plans for Lab Work
This is the first time the problem given to you has really required you to devise an algorithm. We will help you this time
by showing you what an algorithm (for another problem) might look like.
Now write an algorithm for the paper scissors rock game. If you're unsure, get a demonstrator to look at it before you
start coding.
Lab Work
Programming Project PP 5.16 (p. 287). Design and implement an application that plays the Rock-Paper-Scissors game
against the computer. When played between two people, each person picks one of three options (usually shown by a
hand gesture) at the same time, and a winner is determined. In the game, Rock beats Scissors, Scissors beats Paper, and
Paper beats Rock.
The program should randomly choose one of the three options (without revealing it), then prompt for the user's
selection. At that point, the program reveals both choices and prints a statement indicating whether the user won, the
computer won, or if it was a tie.
Continue playing until the user chooses to stop, then print the number of user wins, losses, and ties.
Hint: The user should choose from a list of numbered options, and the choice should be matched against a randomly
generated number representing the computer's choice.
If you find your code is repeating statements, consider whether the repeated statements might be able to be contained in
a method.
A design for the solution to this task is up to you! The output should look like something this:
What is your choice?
1 Play the game
0 Quit
Enter your choice:
1
Playing Paper Rock Scissors. The computer has chosen!
1 Paper
2 Scissors
3 Rock
Enter your choice:
2
You chose Scissors the computer chose Rock. You lose
What is your choice ?
1 Play the game
0 Quit
Enter your choice:
0
You won 0 times
You lost 1 times
You tied 0 times
Bye
Lab Completed
in-lab exercises complete
 method use appropriate
Date
preparation exercises complete  comments
working
submitted
Demonstrator's Initials
Lab7.
Repetition 2
Notes
Readings: Chapter 5, Section 5.8 (pp 252 - 258).
The for loop is particularly useful for the systematic processing of a series of related data. We haven't yet covered the
data structure called an array, which is often processed by a for loop. In the meantime, a String is the closest thing
we have. A String can be thought of as a series of char values, indexed from 0 to length()-1. In this lab you
will use a for loop (or two) to access sequentially each character of a String. You might want to revise the methods
of the String class you used in the Lab6 preparation exercises.
Preparation
1. Write a for loop that displays each integer from 14 to 25 (inclusive). Include any necessary declarations.
2. Exercise Ex 5.10 (p. 282). What output is produced by the following code fragment?
for (int val = 10; val >= 0; val -= 1)
if (val % 4 != 0)
System.out.println(val);
}
3. Exercise Ex 5.17 (p. 283). Write a for loop to print the odd numbers from 1 to 99 (inclusive).
4. Exercise Ex 5.29 (p. 284). Write a method called countA that accepts a String parameter and returns the number
of times the character 'A' is found in the string.
5. Write a method called countChar that accepts a String and a char parameter and returns the number of times
the char parameter is found in the string.
6. What is the minimum number of times the body of a for loop can be executed? Give an example code fragment that
will execute this many times.
Lab Work
Write an application that prints the following output using nested for loop.
Hint: Here is the pseudocode of the above problem.
Repeat the following for row from 0 to 7 {
Pad leading blanks in a row using a loop like this:
for the column from 1 to 7-row
System.out.print("
");
Print left half of the row for numbers 1, 2, 4, up to 2row using a look like this:
for the column from 0 to row
System.out.print(" " + (int)Math.pow(2, column));
Print the right half of the row for numbers 2row-1, 2row-2, ..., 1 using a loop like
this:
for (int column = row - 1; column >= 0; col--)
System.out.print("
" + (int)Math.pow(2, column));
Start a new line
}
You need to figure out how many spaces to print before the number. This is dependent on the number. If a number is a
single digit, print four spaces. If a number has two digits, print three spaces. If a number has three digits, print two
spaces.
Lab Completed
in-lab exercises complete
 working
Date
preparation exercises complete comments
 short string checks
submitted
Demonstrator's Initials
Lab8.
Arrays
Notes
Readings: Chapter 7, Sections 7.1 & 7.2 (pp 372 - 382), Section 7.6 (pp 400 - 405).
If a task has a lot of data associated with it, it is not efficient to store each item in an individual variable. There are
several "data structures" available in java which store related data in an easily accessible way. The array is the first of
these data structures we will look at. Arrays and loops go together - related data items can be accessed sequentially from
within a loop. This lab will introduce you to one-dimensional and two-dimensional arrays.
Preparation
1. For the following declarations, how many array elements are reserved for data and what type of data can be stored?
a. int [] scores = new int [10];
b. char [] grades = new char [100];
c. boolean [] quizAnswers = new boolean [50];
d. int [] primes = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29};
e. String [] choices = {"Delete", "Insert", "Replace", "Search", "Quit"};
f. double [] prices;
prices = new double [readInt ("How many items?")];
2. For the array primes in Question 1 above, indicate the effect of each statement below if it is valid. Rewrite the
statements that are not valid.
a. int sum = (primes[1]+ primes[4]) / 2;
b. primes[0] = primes[9];
primes[9] = primes[0];
c. System.out.println("The last prime number < 30 is " + primes[10]);
d. primes[1 + 4] = primes[1] + primes[4];
e. Use a for loop to find the sum of all the elements.
3. Draw the data structure which is created by this code, and the values that are stored in it:
int size = 4;
int [] [] table = new int[size][size];
for (int row = 0; row < size; row++){
for (int col = 0; col < size; col++){
table[row][col] = row * col;
}
}
Lab Work
Part 1
1. Write an application that reads 10 integers from the user and displays them in the reverse of the order in which
they were read.
Hint: Use an array to store the 10 integers.
2. Generalize the above program to work with any number of integers (inputted by the user).
Part 2
1. Write an application that reads list of names of SOME friends from the user, then prints out how many names
started by the letter 'm' or ‘M’, and also displays these names on the screen.
2. Write an application that reads SOME real numbers from the user, then prints out the largest number on the
screen.
1
2
3
4
5
6
7
8
9
10
11
12
2
4
6
8 10 12 14 16 18
20
22
24
3
6
9 12 15 18 21 24 27
30
33
36
4
8 12 16 20 24 28 32 36
40
44
48
5 10 15 20 25 30 35 40 45
50
55
60
6 12 18 24 30 36 42 48 54
60
66
72
7 14 21 28 35 42 49 56 63
70
77
84
8 16 24 32 40 48 56 64 72
80
88
96
9 18 27 36 45 54 63 72 81
90
99 108
10 20 30 40 50 60 70 80 90 100 110 120
11 22 33 44 55 66 77 88 99 110 121 132
12 24 36 48 60 72 84 96 108 120 132 144
Figure 17-2
Part 3
1. Write a program which uses a two-dimensional array to store then display a multiplication table up to 12 x 12 as
in Figure 17-2.
Note "\t" will print a tab for spacing the output.
Just use an application class, and put all your code in the main method.
2. Write an application that reads a 2-dimensional squared array (number of rows equal number of columns) of
integer numbers from the user, then calculate the summation of the diagonal of this 2-dimensional array and
display the result on the screen.
Note: The summation of the diagonal for the 2-dimensional squared array
Lab Completed
in-lab exercises complete
 multiplication
Date
preparation exercises complete histogram
comments
submitted
Demonstrator's Initials
Lab9.
Methods
Notes
Readings: Chapter 4, Sections 4.1 - 4.4 (pp 160 - 180).
You have been calling methods since Lab 1, and writing void methods since Lab 3. In this lab, we focus particularly
on return methods.
Preparation
1. Consider the class below, and answer the questions.
public class Scope{
private int x = 4;
public void methodOne(){
methodTwo();
methodThree();
}
private void methodTwo(){
int x = 2;
System.out.println(x);
}
private void methodThree(){
System.out.println(x);
}
}
a. Which method can you call from outside of this class?
b. Draw an arrow to the x which is a data field.
c. Put a ring around the x which is a local variable.
d. What will be printed out when methodOne is run?
e. Suppose methodTwo was changed to:
private void methodTwo(){
x = 2;
System.out.println(x);
}
What will be printed out now when methodOne is run?
2. Write a method called doSum which takes two int input parameters, and returns (but doesn't store) their sum.
3. When a method has a declaration or declarations in its parentheses, it is expecting to be sent some data when it is
called. In the previous question, the method doSum is expecting to be sent two integers.
Write a legal method call for the method doSum.
What do you think will happen if you use the method call doSum(); and so don't send the method the
parameters it is expecting?
Lab Work
Part 1
Write a method which computes the binomial coefficient:
then write an application program which uses the method. Try to make the method work for as big n as possible.
Background for Lab 10
Parameters or no parameters - where does the data come from?
Methods can operate on data from a range of sources, both from within the program and without. A method has access
to the data fields of the class and any input parameters. A method can also use data from external sources like the
keyboard (Scanner) or a file (later), from literal values, or from the results of any internal computations including
results from other method calls.
If a method is using data fields that exist as part of the class (the state of the object) then it can work directly with those.
It will not need to use input parameters.
/* NoParameters.java Lab 8 SFDV1003 2007
* Reads kilometres from user and converts to miles
*/
import java.util.Scanner;
public class NoParameters{
private double km; //kilometres
private double miles; //miles
private static final double KM_TO_MILES = 0.6213711922;
//conversion factor
/* no parameters, method works with data fields which are already available to it*/
public void calcMiles(){
miles = km * KM_TO_MILES;
System.out.println("Equivalent miles: " + miles);
}
/* no parameters, method works with objects it creates itself and a data field */
public void readKm(){
Scanner scan = new Scanner(System.in);
System.out.println("Enter the kilometres to convert");
km = scan.nextDouble();
}
}
If the user of an object calls a method on an object and wants to send it information that is not in the object's data fields
then it will need to pass that information as input parameters.
Parameters need to be sent (passed) and received in
matching sets. If a method is expecting to receive
/* Parameters.java Lab 8 SFDV1003
one double input parameter e.g.
2007
public void calcMiles(double km)
* Converts kilometres to miles
the method call must send it one double input
*/
import java.text.DecimalFormat;
parameter e.g. calcMiles(54.2).
public class Parameters{
/* method works with data received as input parameter */
public void calcMiles(double km){ //receives one double
input parameter,
referred to as km
DecimalFormat df = new DecimalFormat();
df.setMaximumFractionDigits(2); //int parameter
passed to
setMaximumFractionDigits
System.out.println(km + " kilometres is " + df.format(km * 0.6214) + "
miles");
}
/*
calls the calcMiles method repeatedly, sending (passing) one double value each time
*/
public void manager(){
calcMiles(50.0); //sends one double value
calcMiles(4.2);
//sends one double value
calcMiles(100.0);
//sends one double value
}
}
Should your method be void or return?
Void methods are performed for their effect. You have had plenty of experience writing void methods already. This
effect may be a change to a data field, or a call (or series of calls) to other methods, or a combination of these. A void
method CANNOT return a value.
/* NoParameters.java Lab 8 SFDV1003 2007
* Reads kilometres from user and converts to miles - same as previous page, different
comments
*/
import java.util.Scanner;
public class NoParameters{
private double km; //kilometres
private double miles; //miles
private static final double KM_TO_MILES = 0.6213711922;
//conversion factor
/* void method, performed for its effect */
public void calcMiles(){
miles = km * KM_TO_MILES;
//change to a data field
System.out.println("Equivalent miles: " + miles); //method call
}
/* void method, performed for its effect */
public void readKm(){
Scanner scan = new Scanner(System.in);
call
System.out.println("Enter the kilometres to convert");//method call
km = scan.nextDouble();
//change to a data field
}
//method
}
Return methods are used when the method produces a single value which is used by some other part of the program.
A return method MUST have its return type specified in the method header, and it MUST return a single value of that
type. Note that in the class below, there are no data fields. The data does not need to be stored.
/* Return.java Lab 8 SFDV1003 2007
* Reads kilometres from user and converts to miles using return methods
*/
The value returned by a method is used at the place
import java.util.Scanner;
where the method is called. We can think of the call to
public class Return{
calcMiles() as a double value.
/*returns a String*/
public String displayMiles(){
return "Equivalent miles: " + calcMiles();
}
/* returns a double*/
public double calcMiles (){
double kmToMiles = 0.6213711922;
//local variable, conversion factor
return readKm("Enter the kilometres to convert") * kmToMiles;
}
We can think of the call to
readKm("...") as a double
value.
/*returns
a double */
public double readKm(String message){
Scanner scan = new Scanner(System.in);
System.out.println(message);
return scan.nextDouble();
}
}
To see the output from this class, make an instance of Return and display the result of its displayMiles method.
Return r = new Return();
System.out.println(r.displayMiles());
Note: If the System.out.println is omitted, and the
call to r.displayMiles() is made as a statement, the
code will compile and run but you will not see the result.
Lab Completed
in-lab exercises complete
 multiplication
Date
preparation exercises complete histogram
comments
submitted
Demonstrator's Initials
Download