```CS 11 – March 3
• Course overview
– Computers & computer science
– Nature of problem solving
• Tomorrow, we’ll continue with
– What software looks like
– Problem-solving procedure
Note: Important terminology highlighted in yellow.
What is a computer?
Memory
CPU
+*
– / %
√  Σ
file
• Machine that stores and
processes information
• With memory, machine
can be programmed.
Memory stores software
and other files.
file
• Information inside
memory is all in binary!
file
• CPU’s job is to obey
instructions from a
program.
What is CS ?
• The study of how we …
– Solve problems
– Represent information
• In problem solving, we’d like:
– Find systematic ways of going about solution
– Correct, quick and informative solutions.
• Information can be:
– Different types: numbers, text, images, sound, the
software itself
– The input and output to a computer program
Problems
• The earliest problems given to a computer were
mathematical.
• Sometimes there is no clean formula
– Many equations can’t be solved analytically. For
example, cos(x) = x. Need to solve numerically.
– Ex. Heat equation is a partial differential equation
(PDE). Most PDEs have to be solved numerically.
– Ex. Calculating a square root.
• And even if there is a clean formula, a computer
Problems (2)
• “Mathematical” problems may at first sound
boring. But they include many useful
applications
– Ex. Finding directions
• Other kinds of problems for the computer
–
–
–
–
–
Games
Record keeping, managing investments, …
Networking, communication
Multimedia (e.g. image processing)
Of course, much more!
Software
• Powerful!
– We get to tell the machine exactly what we want.
– Sometimes, existing programs like Excel or
Photoshop are not enough.
• Program = sequence of instructions for CPU to
obey.
– Works like a recipe.
– A recipe has: ingredients, steps, and result is food!
– A program has: input, calculations, output. 
When we start to look at programs, be on the lookout
for these 3 parts.
I/O
• A program’s input may
be:
–
–
–
–
–
–
–
Numbers
Text
File
URL
Button / click
Image (rarely)
Sound (rarely)
• A program’s output may
be:
–
–
–
–
–
Numbers
Text
File (even HTML)
Image
Sound (rarely)
In this class, we’ll be able to read and create files, interact
with the Web, and create images.
Program parts
• To reiterate: 3 parts are input, calculations,
output.
• We’ll spend most effort on calculations.
– I should give this part a better name, because it’s
mostly not arithmetic. “Logic” or “strategy” may be a
more descriptive name.
• Goal of CS-11: To be able to solve problems
using a variety of I/O and calculation strategies.
Recipes
• Cooking may be a good analogy, because it’s
solving a specific problem “I’m hungry.” 
• What do we see in recipes? Here’s one:
–
–
–
–
–
–
–
Brown the beef 15 min. Drain grease.
Dice carrot, celery, onion (aka “mirepoix”)
Cut up and boil 6 potatoes until soft.
Mash potatoes
Add flour, spices, sauce, mirepoix to beef.
Put meat mixture into casserole, top with potatoes.
Bake in oven at 400 for 30 minutes.
Recipes (2)
• A computer program has some of the same
elements as a recipe…
• In recipes we see:
– Ingredients (the “nouns” of the problem)
– Steps to perform (the “verbs”)
– In some steps, we continue/wait for something
– Although it’s not obvious, sometimes we check things:
• Are potatoes fully mashed?
• Should I add more _____ to the mixture?
Recipes (3)
• But we don’t eat the same stuff every day. Once
we know a few recipes, we can put together a
if
if
if
if
(have all ingredients), make Shepherd’s pie.
(no potatoes), just make soup instead.
(no veggies), make hamburger.
(no beef), make pasta.
• When you view a whole menu as a program,
then “making soup” becomes a sub-program.
– A large program is composed of several parts.
– In industry, sometimes each part implemented by
different people. A kitchen may have many chefs.
Summary
• Computer science is a problem-solving
discipline.
• Many kinds of problems, and the I/O can take
various forms.
• Writing our own software exploits the full power
of the computer!
• Every solution (program) should have a welldefined structure, such as listing the ingredients
and steps for input, calculations and output.
CS 11 – March 4
Overview, continued
• Languages for the computer
• What does software look like?
• Problem-solving procedure
Programming language
• English?
– Ambiguities, relies on context
• Binary?
– Tedious, error-prone!
• In this class, the Java language will be our
vehicle for solving problems.
– Turns out to be easier to write larger programs.
Forces us to have a well-structured solution.
– Many built-in features to support graphics and the
Web. Java was specifically designed for Web
applications.
• Use compiler to translate our program into
binary.
Compiling
Java
program
Java
compiler
Byte
code
Can execute in CPU.
It checks for simple mistakes, and then translates
Practical matters
• Compiler
– This is a program that translates your Java code into
“byte code” that can be executed on the machine.
• Files and folders
– Each source file you type will be a text file whose
name ends in .java
• Two kinds of programs
– Simple – can be accomplished in one sitting, one
source file. Many of our early examples will be like
this.
– Not-so-simple – requires a definite plan. Multiple
source files, one for each “big noun” or class.
Program
• What does a computer program consist of? Has
these parts:
– Begin with a comment describing the problem and
– Tell Java system what built-in libraries we are going to
use (if any).
• special ingredients already prepared by somebody else
• Why is spaghetti so easy?
• Common ingredients we’ll use are System, Scanner, Math.
– Code: use variables and specify steps for our input,
calculations, output
Simple examples
• You don’t have to know a lot of Java to solve
these problems:
– Print a message and halt.
(This program would only do output.)
(Sounds easy, but features input, calcs, output!)
Once we solve this problem, we’d be tempted to
improve on it, and make it more general.
CS 11 – March 5
• You can find class notes on
cs.furman.edu/~chealy/cs11
• Problem-solving procedure.
• Let’s hold off on the “nuts and bolts” until
tomorrow.
Scanner
• When reading input, we can use the built-in
Scanner. (See BasicProgram handout.)
Scanner sc = new Scanner(System.in);
Says that we want to create a scanner, based on the
keyboard input, which Java calls System.in.
int input = sc.nextInt();
• When you want to read an integer, call the function
nextInt();
• Again, don’t worry about every single detail at this point.
Need a plan
• Often a bad idea to rush to keyboard and
start typing code.
• Problem solving procedure:
(See handout)
– design
– implementation
• To learn problem-solving, must practice
– Look at examples ( This is not a theory course  )
– Use built-in features of Java to simpify your soln.
These built-in libraries are collectively known as the
API: Application Programmer Interface.
http://java.sun.com/j2se/1.5.0/docs/api/
• One major skill is identifying the major “nouns”
and “verbs” in problem description.
• In larger programs, structure is based on the
nouns.
• It’s been said that any skill takes about 10 years to
master. In 3 months you won’t be expected to solve
every possible problem. So, be patient with yourself and
have some fun.
• Problem solving isn’t easy. There is no formula that
works in all cases. A problem could arise at any time in
the process. Ask me for help if stuck!
• It’s easier to find a mistake in (English) design than in
the (Java) implementation. This is why the early steps
are important. Again, don’t rush to type code.
Example
• Let’s look at an example problem: The post
office problem.
Ask the user for the number of post cards and
letters that need to be sent, and compute the
total postage, assuming the costs for one of
each are 26 and 41 cents.
• In our solution, we’ll need
– Variables to store numbers.
– Format the output so it looks like money.
CS 11 – March 6
Some nuts and bolts
•
•
•
•
Statements
Variables: names and types
Using Scanner for input
Using printf for output
– Will help us with Post Office problem.
Overview of statements
Fundamental unit of a program
• Must end in a semicolon.
Examples of statements • Assigning a value to a variable
– If this is the first time we’re using the variable, it must
also be declared.
• Input / output
• Calling a function: delegating work to another part of the
program
• Making choices: if-statement, …
• Doing things multiple times : while-statement, …
(this is called a loop)
Variables
• Contain values we manipulate.
• Must be declared before they are used.
• Identifier = name of a variable
– Rule: must begin with letter or _, rest of name may
also contain digits
– Conventions:
• Should have a meaningful “noun” name
• Should avoid _
• Should begin with lowercase letter. If multiple words in
name, capitalize 2nd, 3rd, … words.
Variables (2)
• Formats of declaration
type identifier;
type identifier = initial value;
// better 
• Common variable types:
int, double, char, String
• Other types you may see:
byte, short, long, boolean, float
• Type names beginning with lowercase letter are
the 8 primitive types (small nouns) of Java.
Primitive types
Type
byte
short
int
long
float
double
char
boolean
Purpose
# bytes
Integer
1
Integer
2
Integer
4
Integer
8
Real #
4
Real #
8
single char.
2
true/false
1
range
-128 to 127
+/- 32k
+/- 2 billion
+/- 1019
+/- 1038
+/- 10308
Unicode
Just T or F 
Scanner
Commonly used scanning functions:
•
•
•
•
nextInt() – grab the next integer
nextDouble() – grab the next real #
next() – grab the next word
nextLine() - get the whole rest of the line
• There are also “has” functions (e.g. hasNextInt() )
that test to see if there actually is an integer, real
number, etc. We’ll use these later.
Recap
• Let’s apply what we know
– We can declare and use variables of various types.
– The Scanner can get input of various types.
• Examples
String name = sc.next();
double length = sc.nextDouble();
int size = sc.nextInt();
• Pay close attention to the types. They must
agree. For example, the following is bad:
double height = sc.nextInt();
printf
• Formatted printing
• Designed to print a string in quotes, possibly
with extra information such as variables.
System.out.printf(“Hello.\n”);
• Usually a good idea for the string to end: \n
– Represents the newline character. Whatever follows
will then be on the next line.
• Special codes use the % symbol.
Format codes
•
•
•
•
%d = decimal integer
%f = real number
%s = string
%c = single character (not often used)
Example:
int quantity = 4;
double costEach = 7.99;
double total = quantity * costEach;
System.out.printf(“%d bottles cost \$ %f\n”,
quantity, total);
But the output is \$ 31.960000 
Specifying precision
• The default precision for %f is 6 decimal places.
• You can specify precision by putting the desired
number of decimal places right before the ‘f’.
– Use %.2f to say you want exactly 2 decimal places
– %.1f would mean 1 decimal place.
So we need to change the earlier output statement to:
System.out.printf(“%d bottles cost \$ %.2f\n”,
quantity, total);
(We can do the same thing in Post Office program.)
Summary
• A program is a sequence of statements.
– e.g. assignment stmt., input stmt., output stmt., …
• We use variables
– Variables have a type
– Must be declared before use
• Scanner & printf can handle many types 
CS 11 – March 7
• Postage problem
–
–
–
–
Finish output
Left & right justify numbers.
Some possible (compile) errors.
Special messages, such as under \$10, etc.
• For quick experiments, check out “blank
program”
– Let’s see some built-in Math. (PI, sqrt, …)
– Integer vs. real-number (e.g. win-loss record and %)
CS 11 – March 10
• Finish: integer vs. real-number division
– Can change type of expression
– Look at remainder
• More on the if-statement.
– We’ll use Eclipse: a program that can help us edit,
compile, run and debug software we create.
Expression type
• Sometimes we want to convert integer expression into
real numbers.
9 / 5 equals 1, which is probably not what we want!
• Use real-number constant.
9.0 / 5
• But what if we want a/b and they’re both int?
– Can multiply by 1.0
1.0 * a / b
– Can use a cast before the variable. (double) a / b
I include extra parentheses if I’m ever in doubt about
the precedence. But don’t type: (double) (a / b) !
/ and %
• Integer division is still useful
/ gives quotient and % gives the remainder.
• Ex. Counting change
– Given # of cents (1-99), tell how many of each type of
coin.
• Ex. If num is an integer, what are…?
num % 10
num % 100
If-statement
• As we saw before, used to ask a question
if (amt < 10.00)
no credit card
if (num < 0)
number is negative
• Often we have an alternative to handle. So we
use the word else.
if (hours > 40)
overtime pay formula
else
regular pay formula
// Let’s work out this example!
Overtime
• Hourly employee.
hours = Hours worked
rate = Hourly rate
• Let’s assume overtime rate is 1.5x
if (hours <= 40)
pay = hours * rate;
else
pay = 40 * rate + (hours – 40) * (rate * 1.5);
Divisibility
• Often we want to know if an integer is divisible
by something.
– For leap year, divisible by 4.
– Even number: divisible by 2.
– Prime number: divisible by almost nothing!
• We use % with an if-statement. Here is even:
if (num % 2 == 0)
System.out.printf(“number is even\n”);
else
System.out.printf(“number is odd\n”);
Example: F/C
• Design a program that allows the user to convert
from Fahrenheit to Celcius, or the other way
around.
Do you want
F  C or C  F
?
Do
FC
Do
CF
Lab
• Each program should be in its own folder.
• You’ll be given incomplete source files.
– Design phase – We would type only the minimal
• Eclipse is program we’ll use for implementation.
– Open Eclipse, create “project”, telling it where your
source files are.
– Compile and run whenever you like.
– Finish implementation here.
CS 11 – March 11
• Recap of yesterday
• Types of errors
• Other print functions
• Strings 
Recap
• Some ideas from lab
– Paint program: we had intermediate calculations for
area of room, gallons of paint… finally cost of paint.
– If you need to round a real number to an integer
• Can use Math.round( ), Math.ceil( ) or Math.floor( )
• Can cast a double as an int: e.g. (int) 8.7 equals 8.
– We didn’t do any error checking of input.
• Closer look at leap years
– The if-statement needs a more thorough condition.
We’ll need special operators for:
AND……… &&
OR……….. ||
Multiple if’s
• The FC program had a menu, and the user could choose
1 or 2. What if we had 3 choices?
if (choice == 1)
...
else if (choice == 2)
...
else
...
// Handle case # 3.
• Analogous example: a number could be positive,
negative or zero.
Errors
There are 3 kinds of errors (mistakes)
• Syntax errors
– Usually typos in code (misspelling name, missing
operator or ; )
• Run-time errors
– Program stops abnormally. Could be bad input,
uninitialized variable, wrong type, …
– Divide by 0, sqrt(negative), etc.
• Logic errors
– Incorrect formula, wrong value being printed out, etc.
Printing output
• In general, printf is the best way. 
• But sometimes all you want to do is print out one value,
and you don’t care about formatting. There are more
primitive print functions:
– print
– println
The only difference is println automatically gives you \n.
• print/println are good for printing boolean:
System.out.println(4 > 6);
String
• Data type used for text (words, etc.)
• Has many built-in functions
• Called a string because it just “strings” many
characters next to each other.
String s = “shark”;
Index:
0
1
2
3 4
s
h
a
r
k
String functions
• Simple built-in functions:
length( )
charAt( integer )
// starts with 0
+ sign is used to concatenate
• Examples
String s = “Hello”;
s.length() would return the value 5
s.charAt(1) would return ‘e’
s + “ Java” would be “Hello Java”
functions (2)
• More common operations
– indexOf ( pattern ) = find something in the string
– substring (start, end) = give me part of string
– substring (start) = give me rest of string
• Examples with s = “hello, world”
s.indexOf(“,”) equals 5
s.indexOf(“duck”) equals -1
s.substring(7, 10) equals “wor”
s.substring(4) equals “o, world”
Using +
• Let’s reverse somebody’s name
System.out.printf("Enter your first & last name: ");
String first = sc.next();
String last = sc.next();
String fullName = last + ", " + first;
• Pig Latin 
• Note that you may concatenate numbers into strings.
num = 5;
message = "answer is " + num + "\n";
• Be careful…
"2" + 3 becomes "23" not "5"
CS 11 – March 12
• Strings
– Comparing
– Review StringFun handout
• Being able to repeat steps
– Lots of data / input
– Avoid tedium using a loop
Comparing strings
• equals( another string ) – returns boolean
s = “Hello”;
if (s.equals(“hello”)) ...
• compareTo( another string ) – returns int
Useful for alphabetizing!
– Return value 0 ……………. strings are equal
– Return value negative…… first string come earlier in dictionary
– Return value positive…….. first string comes later in dictionary
This makes much more sense with an example!
• Note: don’t use (==, <, >) for Strings.
Examples
String s1 = “cat”;
String s2 = “cow”;
int diff = s1.compareTo(s2);
s1 = “fish”;
s2 = “files”;
diff = s1.compareTo(s2);
Index
0
1
2
Index
0
1
2
3
s1 =
c
a
t
s1 =
f
i
s
h
s2 =
c
o
w
s2 =
f
i
l
e
subtract
0
-14
0
7
subtract 0
Working from left to right, we subtract character values until we see
a non-zero result. If we reach the end of both words at the same
time, return 0 because they’re equal.
4
s
String handout
• StringFun.java features these String functions:
–
–
–
–
–
–
–
–
charAt
equals and equalsIgnoreCase
compareTo
startsWith and endsWith
length
indexOf and lastIndexOf
substring
replace
Next problem
• How would you add 5 numbers?
int
int
int
…
int
first = sc.nextInt();
second = sc.nextInt();
third = sc.nextInt();
sum = first + second + … + fifth;
• This approach “doesn’t scale”. What if we wanted 50
numbers? (Java doesn’t understand “…” )
• We find ways to simplify our work, avoid tedium.
Loop
• When we need to do something repetitive, use a loop.
• while-statement, similar to if-statement.
while ( condition )
statement;
– We do the statement repeatedly as long as condition is still true.
– The body is 1 statement or a block of statements.
• There are other kinds of loops, but while is simplest.
Counting
• The simplest example of a loop is being able to
count (e.g. 1 to 10)
int num = 1;
while (num <= 10)
{
System.out.printf("%d\n", num);
num = num + 1;
}
• Let’s try to generalize. Print odd numbers, reverse, sum.
// When we read input, need to COUNT how many
// numbers read, and keep track of sum.
int count = 0;
int sum = 0;
while (count < 5)
This solution
{
scales well for
int newNumber = sc.nextInt();
larger input.
sum = sum + newNumber;
count = count + 1;
}
System.out.printf("The sum is %d\n");
CS 11 – March 13
• Review loops (while-statement)
– Ex. How to count from 1 to 10 ?
– Common mistakes to avoid
– Examples using strings.
• Read input from a file
• Sometimes we also need a lot of similar
variables.
– An array is more efficient.
– Like a string, but may contain #’s rather than
characters.
Common mistakes
• Initially false
num = 1;
while (num > 10) …
• Infinite loop !
num = 1;
while (num <= 10)
{
System.out.printf(“%d\n”, num);
}
• Off by one
num = 1;
while (num < 10)
{
System.out.printf(“%d\n”, num);
num = num + 1;
}
num = 1;
while (num <= 10)
{
num = num + 1;
System.out.printf(“%d\n”, num);
}
String examples
• Given a word, how many E’s does it have?
– We can look at one letter by using charAt.
– Use == to compare primitive types like char.
• Reverse a word.
– Again, need charAt to obtain 1 letter at a time.
– Need to use + to help us build a new word.
CS 11 – March 14
File I/O
• Similar to regular I/O with Scanner & printf.
• File input
– FileInputStream
– FileNotFoundException
• File output
– We don’t do this as often.
– PrintStream
Why?
• With loops, we can easily handle lots of I/O.
– We don’t want to type much input.
– Can’t fit all output on screen.
• In some applications, we need to modify a file.
–
–
–
–
Numbering the lines
Cryptography
Text processing: spell checking, replacing words, …
Database operations: sort customers by state
File input
• Special ingredients
– Again, we’ll use the Scanner
– Also need FileInputStream
– FileNotFoundException: When opening input
file, there’s possibility that the file doesn’t
exist.
Scanner in = new Scanner(new FileInputStream
(“input.txt”));
Examples
• Find average of long list of numbers.
– Do we know how many numbers in advance?
– Need sum
– Need to count.
• Computing overall win/loss records.
– Need to convert String to integer
File Output
• Special ingredient: PrintStream
PrintStream out = new PrintStream(“output.txt”);
…
out.printf(“%d\n”, 2 * num);
• Simple examples:
– Print numbers 1-100 to a file
– Read input file of numbers. Double each number,
and write results to a second file. (Sounds simple,
but cryptography is analogous.)
CS 11 – March 17
• We can solve almost any simple problem.
–
–
–
–
I/O: keyboard, screen and files
Calculations
Making choices (if)
Repeating calculations/steps (while)
• Lots of data
– Use loop for input and calculations
– Store I/O in file
– Where can we keep all this data while program is
running?
Doing more
• We can find average of a lot of numbers.
• What if we also wanted other statistics?
(max, min, median, s.d., top 10%, etc.)
– Or, do all these calcs during input. (not always possible)
– Or, store the numbers as we read them.

• How do we declare, say, 50 variables without
running out of names?
Array
• Many variables for the price of one.
• For example,
int [ ] score = new int [100];
defines an array of 100 integers called score.
The cells in the array are score[0] thru score[99].
• Sometimes we already know what goes in the array.
int [ ] areaCode = { 864, 803, 843 };
• We almost always use a loop with an array.
int index = 0;
while (index < 100)
score[index] = sc.nextInt();
List of numbers
How do we do the following…?
• Find sum and average. √
• Find largest number.
• Find smallest number.
• Count how many are above/below threshold.
• In each case, we can use a loop.
A note on I/O
• Sometimes we need 2 scanners
– One to read keyboard (console) input
– One to read from a file
– Ex: Ask user for file name, then open that file.
• You can even write to multiple files.
– Rarely needed.
Practice
• Let’s spend some time working on the skills we
know.
• In future weeks we’ll see more:
–
–
–
–
–
–
Random numbers – for games!
Better ways to loop, make choices, store data
Applets
Using the Web
Dealing with unexpected input
Larger problems broken down into multiple source
files (like a meal with several courses)
CS 11 – March 18
• Error checking: use a loop and boolean variable
needInput = true
As long as needInput is still true…
{
Ask the user to enter input.
if (input is valid)
needInput = false
else
print error message and try again.
}
Example
• We want value to be a positive number.
int value = 0;
boolean needInput = true;
while(needInput)
{
value = kbd.nextInt();
if (value > 0)
needInput = false;
else
System.out.printf(“Sorry, your input is “ +
“invalid. Try again.\n”);
}
CS 11 – March 19
• Fibonacci sequence (25 numbers)
first = 1
second = 1
Print first and second.
do the following 23 times:
next = first + second
Print next.
first = second
second = next
In general, we should
strive to have solutions
that are easy to understand
If you have a “clever”
a careful comment
explaining it.
Square root
old guess = 1
new guess = 0.5 * (old guess + A / old guess)
while (| old guess – new guess | > .005)
old guess = new guess
new guess = 0.5 * (old guess + A / old guess)
Print new guess.
To do absolute value, use Math.abs().
√5:
1.000
3.000
2.333
2.238
2.236
CS 11 – March 20
• Search an array
– Ex. Finding a negative number, or a specific
value.
– 2 possible questions
• Is it there – yes/no
• Where is it? -- similar to indexOf for strings
Example Search
int index = 0;
boolean found = false;
while (index < 10)
{
if (a[index] < 0)
found = true;
}
In this example, we are
seeing if an array a of 10
integers contains a
negative value.
If we want the actual
location of the negative
entry, we’d replace the
“found = true” with
“location = index”. (The
location would start at -1
before loop.)
CS 11 – March 25
• Until now, we’ve been solving “short” problems.
• By means of some examples, let’s begin looking
at how we tackle larger questions.
• Look at TriangleDriver.java
– What does this program do?
– What is missing?
Approach
• In this “triangle” program, we need 2 source files
– TriangleDriver.java = main program
– Triangle.java = implementation details
• In Object-oriented design, we generally follow
these steps:
– Design the overall solution
– List what we want in some new data type.
– Implement all the features of that new data type.
OO Design
• Object-oriented design
– Every program is about 1 or more “big nouns”
– These big nouns are called classes.
– Sometimes the class already exists, e.g. String
• Otherwise we create our own classes.
– Generally we need 2+ source files.
• Class
– Essentially a data type (e.g. String, Account, Triangle)
– Consists of its own attributes and operations
– Need to do some examples.
Triangle
• Let’s continue with Triangle example
– Driver gives us clues about what we want.
• A triangle’s attributes & operations:
– What information is contained in a triangle?
– What are their types?
– What operations do I want to do on triangles?
• Major advantage: Once we create Triangle.java,
we can re-use it in many different programs!
– In a future program, we may want to compare.
Functions
• In the class implementation file, we need to
define functions. (a.k.a. methods)
– These functions get used in the driver file.
• Function definition looks like this:
public <type> name ( formal list of parameters )
{
statements, calculations...
almost all functions “return” a value
}
Triangle functions
• This example is rather simple. Nearly all the
functions:
– Need no parameters, because they are questions
– Returned a boolean value, because they were
• Constructor is special kind of function
–
–
–
–
We write this one first!
It’s purpose is to create/initialize information.
Does not have a return type
Does not return any value
CS 11 – March 26
Object-oriented strategy
• Overview √
– Solutions separated into 2 source files
• Function concepts
– Parameters
– Return value
• Designing a class
– Attributes and operations
Functions
•
•
•
•
Encapsulate a set of calculations
Parameters (how many, what type)
Return value (what type)
7
4
8
findMax( )
8
String examples
String s = “ice cream cone”;
• A string object can call its own functions.
length
14
“tree”
4
charAt
equals
false
‘c’
5
9
substring
“ream”
Class design
• How do we design a class (e.g. Account) ?
– Ask what attributes you need. What makes each
bank account distinct?
– Need a way to create a single account object:
Constructor
– Other functions: deposit, withdraw, accrueInterest,
transferTo, getBalance, writeCheck
Account attributes
• Each account needs this information:
– Current balance
– Interest rate
– Current check number
• What type should we use for each attribute?
• When we write the class, attributes go first:
public class Planet
{
Constructor
• This is a function that initializes the attributes.
– Usually we initialize based on parameters being
passed from the main() function. The main() function
might specify that it wants an account with \$500 at
2% starting at check 101. For example,
Account ken = new Account(500, 2, 101);
public Account(double init, double r, int num)
{
balance = init;
rate = r;
checkNumber = num;
}
Account functions
• How should the other functions work?
– deposit
– withdraw
– accrueInterest
• Need to recall how interest rate is represented!
– transferTo
– getBalance
– writeCheck
• In other words, for each function:
– Does it change any attribute values?
– Does it need parameters?
– Does it return a value?
CS 11 – March 27
• Program design
– Defining a class with: attributes and operations
– Continue with Account example
• Problem solving with OO approach
• Constructors
• Constants
Functions, continued
• For each function we need, often helps to ask:
– Does it affect an attribute value?
– Does it need any parameters?
– Will it return a value?
• Account class functions:
–
–
–
–
–
Deposit, withdraw √
accrueInterest
getBalance
writeCheck
transferTo
Using the Account
• Once Account.java is finished, we can solve any
problem that needs accounts. In Driver.java:
– Create account objects
– Call other account functions
Account ken = new Account (500, 2.5, 101);
Account mary = new Account (1000, 3.0, 101);
ken.deposit(20);
mary.withdraw(75);
ken.transferTo(mary, 100);
System.out.printf(“\$ %.2f\n”, mary.getBalance());
Problem
• Let’s revisit an earlier problem, but organize our
solution around 2 source files.
– Given the dimensions of a room, find the cost to paint
the walls.
• The “big noun” is the Room class. We could
design it this way:
– attributes: length, width, height
– constructor
– other functions: findWallArea, findCost
Outline
public class Room
{
private int length;
private int width;
private int height;
// Need constructor
// findWallArea
// findCost
}
Inside the main program we
want to do this:
Room r1 = new Room(12,9,8);
double cost = r1.findCost();
// print the cost...
Constructors
• There are 3 kinds of constructors, depending on
what parameters we want to pass.
– Initial-value: parameters are used for the initialization
Room r1 = new Room(14, 18, 9);
– Default: takes no parameters. Uses “default” values
to put into the attributes.
Room office = new Room();
– Copy: make a duplicate of an existing object
Room kitchen = new Room(office);
// Initial-value constr.
public Room(int x,
int y,
int z)
{
length = x;
width = y;
height = z;
}
// Default constructor
public Room()
{
length = 30;
width = 20;
height = 10;
}
// Copy constructor
Public Room(Room r)
{
length = r.length;
width = r.width;
height = r.height;
}
Constants
• Some quantities should not change during a
program.
– Interest rate on an account
– Cost per square foot to paint
– Cost of first-class stamp
• How to declare constant:
public static final <type> <name> = <value>
public static final double interestRate = 3.75;
public static final int numCards = 52;
Constants (2)
• A closer look at the declaration.
public static final double interestRate = 3.75
public = this constant is visible everywhere
static = constant is shared among all objects in this
class, so we save memory space
final = it will never be set to a different value
For example, note how we’ve used .
CS 11 – March 28
• Examples using class design
–
–
–
–
Cost of building a house (handout)
Road trip: Cost per mile of driving a car.
Calculate amount of time to fill a pool.
Adding amounts of time, such as 6h13 + 2h27
• For each case, what is the “big noun” ? Then:
– Attributes (name and type of each)
– Operations we need (parameters, return type, etc.)
CS 11 – March 31
• Functions returning objects
– Finish example with creating new object in instance
function. (sum of 2 times)
– Fraction class
• Array of objects
– Fortunately, arrays can handle objects just as easily
as primitive-type variables.
Time sum
// We want to add “this” time to some “other” time.
// What’s unusual is creating a 3rd time object.
public Time sum(Time other)
{
int totalHour = this.hour + other.hour;
int totalMin = this.min + other.min;
if (totalMin >= 60)
{
totalMin = totalMin – 60;
totalHour = totalHour + 1;
}
return new Time(totalHour, totalMin);
}
Fraction class
• Attributes
– Numerator
– Denominator
• Operations
–
–
–
–
–
Constructors
Multiply
toString
reduceMe (let’s not do this one yet)
• If a function returns an object, we should allocate space for it.
Arrays
• It’s a lot more interesting
if we could have an array
of objects.
• Declaration just like
arrays of primitive type:
int [] a = new int[10];
Card [] hand = new Card[13];
Team [] team = new Team[30];
• Array operations often
use loops.
Team
W
L
OT
PIT
46
26
7
MON
44
25
10
CAR
42
31
6
NJ
43
28
7
Array Example
• The weather bureau publishes daily numbers on
– High temp, low temp, how much rain
– These can be attributes of a “Day” class
• At end of month, we can find out the following
–
–
–
–
Highest, lowest temp of month
How much heat or a/c was needed
Total rain
These can be functions defined in a “Month” class
Design
• Driver
– Create Month object
– Print out the following:
•
•
•
•
•
march.findMax()
march.findMin()
march.findTotalRain()
march.findHeat()
march.findAC()
• Month
– Attribute
• Array of Days
– Operations
• Constructor initializing
• The “find” functions
• Day
– Attributes
• High temp
• Low temp
• Rain
CS 11 – April 1
• Review steps for lab #3
• Finish monthly climate problem.
– Array of objects
– Convenient to organize into 3 source files.
– Searching an array of objects is similar to searching
array of numbers, or characters in a string.
• findMax() – search array for an attribute
• findMin() – search array for an object
• No class tomorrow; please submit homework design by
Thursday.
Team.java
• Declare attributes: 1 string, 3 int
• Declare constant GOOD = 95
• Initial-value constructor
– This is where attributes are initialized.
• findTotalPoints()
• isGood()
– Since we need to know the number of points, we
need to call findTotalPoints( ) within isGood( ).
– You don’t need to make points an attribute, because it
can be derived from other values.
Driver.java
•
•
•
•
Ask user for number of teams
Use nextInt( ) to read this number  numTeams
Initialize count and numGood to 0
Set up while-loop to run numTeams iterations:
–
–
–
–
–
Ask user for a name and 3 numbers
Create team object by calling Team constructor
Call toString( ) to print out the object.
Call isGood( ), and if true, increment numGood
• Print the number of good teams
Driver2.java
Change program to use file I/O.
• Ask user for names of input & output files
• Read these names from keyboard.
• Open the input and output files.
• Read first number from file  numTeams
– Take out prompt asking user for this number
• Inside while loop:
– Change the scanner calls so we read from the input
file instead of from the keyboard
Monthly climate
• The most interesting part of the program is the
Month class.
– Each line corresponds to one day.
– Read the 4 numbers, create Day object, put in array.
• Traversing an array
– I implemented findMax( ) and findMin( ) differently so
you could see the difference between finding an
object versus just one attribute value.
– findTotalRain( ) just sums the rain attribute for each
Day.
CS 11 – April 3
• Pass array to function – yes
• Some common mistakes
Array parameter
• You may pass array to a function just like any
other object.
double [] tempArray = new double [12];
...
City c = new City (name, tempArray, rainArray);
• The formal parameter must include: base type
of the array, empty brackets, param name.
public City(String name, double [] tempArray,
double []
rainArray)
What’s wrong…?
System.out.printf(“Enter number of people:
int numPeople = in.nextInt();
if (numPeople = 0)
System.out.printf(“Can’t be zero!”);
“);
match = true;
What’s wrong?
// Let’s see if c contains a vowel:
if (c == ‘a’ || ‘e’ || ‘i’ || ‘o’ || ‘u’)
System.out.printf(“Yes, it’s a vowel!\n”);
-------------------------------------------// See if user wants to quit program.
char input = in.next().charAt(0);
if (input != ‘Y’ || input != ‘y’)
System.out.printf(“Thanks for staying!\n”);
What’s wrong?
// Need to do something on the last day of
// months that have 30 days!
if (month == 4 || month == 6 ||
month == 9 || month == 11 && day == 30)
...
----------------------------------------------Let’s put the sum of a and b into a String.
What’s wrong?
// Let’s count by odd numbers up to 100.
int count = 1;
while (count != 100)
{
System.out.printf(“%d\n”, count);
count += 2;
}
------------------------------------------------// Anything dangerous here?
int sentenceEnd = s.indexOf(“.”);
String s2 = s.substring(0, sentenceEnd);
What’s wrong?
// Let’s add up the numbers from 1 to max.
// There are 2 problems!
int num = 1;
int sum = 0;
while (num <= max)
sum += max;
num += 1;
System.out.printf(“The sum is %d\n”, sum);
What’s wrong?
// A “CLP” checker
if (credits >= 88 && clp >= 27)
return “senior”;
else if (credits >= 58 && credits < 88 &&
clp >= 18 && clp < 27)
return “junior”;
else if (credits >= 28 && credits < 58 &&
clp >= 9 && clp < 18)
return “sophomore”;
else
return “freshman”;
CS 11 – April 7
• Random Numbers
– Used extensively in games, such as rolling dice.
– Monte Carlo simulations
• How to:
– Create new Random object (built-in class)
– If you want integer: nextInt(n) returns 0 to n-1
– If you want real-number: nextDouble() returns 0 to 1
• Examples
– Dice game
– Guessing game
things to come
• In the next few weeks
–
–
–
–
StringTokenizer (?)
ArrayList
Card: switch stmt
Different kinds of loops
• Also, nesting the loops
• ++ and - - (also discuss
prec/assoc?)
• Application – binary
search
– Multi-dimensional arrays
– Games (can do poker now
I think)
– Random numbers; monte
carlo simulation
– For hangman or binary
search(?): unicode.
– Reinforce OO
• Get & set
• Possible assignments:
– Hockey +/– Game: e.g. Othello or
Blackjack.
afterward
• Which then leaves fun stuff. For example,
–
–
–
–
–
–
Applets
Creating images
Inheritance
Interfaces
Exceptions
Web robot
CS 11 – April 8
• Recap lab
– Important aids to productivity
– Review operators
– Loops
• Different kinds of loops
• Using multiple loops
– Making choices
Lab review
• Declaring objects (and arrays):
– If a local variable inside some function:
Random gen = new Random ();
int [] a = new int [10];
Card [] deck = new Card [52];
– If an attribute of a class, split it up. For example:
private Random gen; as an attribute and
gen = new Random(); inside constructor.
• Obtaining value from array…
deck[0], deck[51], deck[index]
Shortcut operators
• Assignment operators
– A binary operator immediately followed by ‘=‘
+=
-=
*=
/=
%=
etc.
– “count = count + 1” becomes “count += 1”
– “amount = amount * 1.06” becomes “amount *= 1.06”
• Increment and decrement (++ and --)
– Used for adding or subtracting 1.
– Can only be used on single variable. May go before
or after ( ++count or count++ )
Order of ops
• Do operations in this
order:
*/%
+< > <= >= == !=
&&
||
= += -= *= /= %=
• Examples:
a
b
c
c
= 2;
= 3;
= 5;
*= a + b;
g = a > b || b > c;
Associativity
• Order of operations when you have 2 operators
of the same level of precedence.
• Most operators are “left-to-right” associative
8 – 4 + 3 means (8 – 4) + 3
• Assignment operators are “right-to-left”
a = b = c means a = (b = c)
a *= b += c means a *= (b += c)
More on ++, -• Be careful if ++ or -- is used in a larger expression.
++a means increment, then evaluate.
a++ means evaluate, then increment.
• Example:
a
d
e
f
=
=
=
=
b
2
2
2
=
*
*
*
c = 3;
++a;
b++;
(c+1);
// a = 4. Then, d = 2*4 = 8.
// e = 2*3 = 6. Then, b = 4.
// f = 2*4 = 8. c is unchanged.
• To minimize confusion, I use prefix form (++a) all the
time unless I really need suffix form (a++).
Examples
48 / 6 / 3
a
b
c
a
=
=
=
=
1;
2;
3;
b = c;
a
b
c
b
a
c
= 4;
= 3;
= 2;
+= c;
-= b;
*= a + b;
a = 4;
b = 3;
c = 2;
--c;
++a;
System.out.printf(“%d\n”,
a * --b + c++);
Useful example
• It’s unusual that we’d use ++ inside a larger
expression, but here’s an example:
count = 0;
while (sc.hasNext())
{
wordArray[count++] = sc.next();
}
Loops
• There are 3 kinds of loops in Java
– While loop
9%
– For loop
89%
best when you know # iterations in advance
– Do-while loop (rare)
2%
always does at least 1 iteration
CS 11 – April 9
• Loops
– while loop (done)
– for loop
– do-while loop
• break and continue statements
– Used for terminating a loop or just one iteration
“For” loop
• Many times we want to say “for each element in the
array” or “for each number the user enters.”
• Perfect when you how many iterations you want.
• General layout:
for ( initialization ; condition ; increment)
BODY
• Example:
for (int i = 1; i <= 10; ++i)
System.out.printf(“%d\n”, i);
How it works
• A for-loop has 4 parts.
for ( 1 ; 2 ; 3 )
4
(exit loop when false)
For = while
• For-loop:
• Equivalent while-loop
for ( 1 ; 2 ; 3 )
{
4
}
1
while ( 2 )
{
4
3
}
Example
• For-loop:
• Equivalent while-loop
for (i = 0; i < s.length(); ++i)
{
if (s.charAt(i) == ‘t’)
++count;
}
i = 0;
while ( i < s.length() )
{
if (s.charAt(i) == ‘t’)
++count;
++i;
}
Notice the location of the
increment is different. Less
likely to forget it if it’s at the top!
Optional parts
• It turns out that all the parts of a for-loop are
optional. For instance we can have…
for ( ; i < 100; ++i)
for ( ; sc.hasNextInt(); )
// like a while loop
for ( ; ; )
// forever!
If the condition (#2) part is missing, then it’s assumed to be
true.
do-while
• Think of it as an “upside-down” while loop.
• Just like a while loop except
– The condition comes at the end.
– We’re guaranteed to do at least 1 iteration.
• General format:
do
{
body
} while (condition);
Example
boolean needInput = true;
do
{
System.out.printf("Enter a positive number: ");
value = in.nextInt();
if (value > 0)
needInput = false;
else
System.out.printf("Sorry, try again...\n");
} while (needInput);
Style
• do-while loops are rare. If you use one, make
sure the end of the loop looks like this:
} while (condition) ;
and not like this:
}
while (condition);
Or else we would confuse the reader into
thinking you have an infinite while loop!
Taking control!
• There are 2 special statements that can be used with
loops: break and continue.
• “break” is used when you want to abandon a loop. For
example, in a search:
for (int i = 0; i < a.length; ++i)
if (a[i] == 0)
{
found = true;
break;
}
// get me out of here!
break vs. continue
• So, “break” means that the loop is over.
• On the other hand, “continue” says that the
current iteration is over, and we should
immediately start the next iteration.
• Example – Fibonacci handout
– Stop printing at 8000
– Skip all 3 digit numbers!
CS 11 – April 10
• Let’s practice with OO, arrays and for-loops.
• Process scores from a diving competition:
–
–
–
–
Each diver has 7 scores,
find the average
Find the average, discounting the highest and lowest scores
Find the average, discounting dishonest judge [3].
– If we have time, given several divers, find the best average.
CS 11 – April 11
• Nested loops
– “Loop within a loop”
– Allows computer to do a lot of work!
– Useful for multi-dimensional arrays
• Tic-tac-toe, connect 4, chess, …
• Airline and room reservations
– Useful for I/O for rows & columns of data
• 2-D arrays
– How to declare, allocate, initialize, and use
Nested loop
the idea:
• Don’t confuse nested loop with
consecutive loop
– For each week…
• for each day
– For each line…
• for each word on the
line
– For each building
• For each room
for (int i = 0; i < 10; ++i)
++count;
for (int j = 0; j < 20; ++j)
++count;
for (int i = 0; i < 10; ++i)
for (int j = 0; j < 20; ++j)
++count;
Example
• Let’s print out a multiplication table
for (int i = 1; i <= 10; ++i)
{
for (int j = 1; j <= 10; ++j)
{
System.out.printf("%d ", i*j);
}
System.out.printf("\n");
}
If the loop body
has only one stmt,
{ } are optional.
Can we do this?
• How can we get a nested loop to print out these
numbers:
1 2 3 4 5
1 2 3 4
1 2 3
1 2
1
• Observe how many lines of output we need
(outer loop), and what the last number on each
line should be (inner loop).
More examples
• This is good practice
10 15 20 25 30
15 20 25 30
20 25 30
25 30
30
Outer loop: what distinguishes each line?
The starting number varies from 10 to 30
Inner loop: what numbers get printed per line?
From the “row number” up to 30.
CS 11 – April 14
• Nested loops
– Ex. Creating a checkerboard pattern
• 2-D arrays
– Useful for board games, creating images
– Declare, allocate, initialize, use
– Accessing elements
2-d patterns
• How can we create these:
X X X X X X X
X X X X X X
X X X X X X X
X X X X X X
X X X X X X X
X X X X X X
X X X X X X X
XXXX XXXX XXXX XXXX
XXX XXXX XXXX XXXX
XX XXXX XXXX XXXX X
X XXXX XXXX XXXX XX
XXXX XXXX XXXX XXX
XXXX XXXX XXXX XXXX
XXX XXXX XXXX XXXX
XX XXXX XXXX XXXX X
Arrays
• Nested loops are very practical for
multidimensional arrays.
• Declare & allocate
int [][] a = new int [8][10];
• Initialize
for (int i = 0; i < a.length; ++i)
for (int j = 0; j < a[0].length; ++j)
a[i][j] = i * j;
• Use
– Ex. We may want to search for the number 15.
Search
int desiredValue = 15;
boolean found = false;
for (i = 0; i < a.length; ++i)
{
for (j = 0; j < a[0].length; ++j)
{
if (a[i][j] == desiredValue)
{
found = true;
}
}
}
Due to space
limitations, declarations of
i and j are not shown.
so that we store the
location of the
desired number.
• If you use break,
note that you can
only exit one loop at
a time. We’d need a
2nd break statement
to get out of the outer
loop.
Tic-Tac-Toe
• Set up board and assume ‘X’ goes first.
• Loop
–
–
–
–
Print the board
Prompt the appropriate user to move.
Attempt to place token onto a square. (error checking?)
See if the game is over.
• Board implementation
–
–
–
–
–
2-D array of character (‘X’, ‘O’, or blank)
Keep track of how many tokens on board
function to place token onto board  return boolean
*** function to detect if there’s a winner
toString
CS 11 – April 15
• What is bug in ttt program?
• Recap error checking
– Scope of variables
– Definite assignment
• Switch statement
Error checking
needInput = true
while (needInput)
{
int length = ...
int width = ...
// check to see if both are valid...
}
Box b = new Box(length, width);
Error: length and width variables are “out of scope”
Move their declarations to before loop
Must give them initial values (e.g. 0).
Switch statement
• Variant of the if-statement
– Useful when you have a lot of “cases” to consider.
– Saves you having to type “else if” so many times.
• Restrictions
– Can only compare a single variable/expression
– Can only compare “integral” types (int, char)
– Can only compare with ==
• Cases are separated by “break” statement.
Example
// Let’s find the number of days in a month.
switch (monthNum)
{
case 2: days = 29;
break;
case 4:
case 6:
case 9:
Can combine several cases
case 11: days = 30;
break;
default: days = 31;
break;
“default” means
“for all other cases”
}
Example (2)
// Let’s convert suit
switch (suitChar)
{
case ‘h’: suitName
break;
case ‘d’: suitName
break;
case ‘s’: suitName
break;
case ‘c’: suitName
break;
}
letter to string.
= “heart”;
= “diamond”;
= “club”;
Card class
• For card games, we need a Card class
– Attributes for denomination & suit (e.g. Q-d) √
– Many operations!
• Create a card, given integer value 1-52.
• Return some attribute, e.g. is it a face card? √
• Comparisons: sameSuit, sameDenom, one higher denom
• Other possible classes
– Deck class, for shuffling and dealing.
– Hand class
• isFullHouse, isFourOfKind, isFlush …
Poker
• Poker class
– Create 5 cards, make a hand and evaluate it.
• Hand class
–
–
–
–
Attributes: 5 cards objects
I decided not to use an array
Functions for every possible poker hand
Assumes the 5 cards are in descending order 
• Card class
– Helper functions for Hand
– Watch out for “1 higher than” !
CS 11 – April 16
• Poker version #2 has 4 classes
–
–
–
–
Driver
Card: new constructor that takes integer (1-52)
Hand
Deck – so that we can “shuffle” all the cards
• Things to note
– How to shuffle
– How we use switch statement
– Can we modify program to allow user to replace
card?
Random card
• To simulate the effect of “dealing”, we want to
– Pick a random number in the range 1..52
– Convert this number to a card
• This could be another initial-value constructor
• There are 4 possible suits
• There are 13 possible denominations
Here’s one way to do it:
Clubs are 1-13
Diamonds are 14-26
Hearts are 27-39
CS 11 – April 17
• Sorting an array
• Modify poker program so it allows user to
replace cards.
Sort
• Arrange in either ascending or descending order
• There are many sorting methods!
For fun, check out: http://cg.scs.carleton.ca/~morin/misc/sortalg/
• Here is a simple one:
– Look at all pairs of values in the array
– If any pair is out of order, swap them.
• Example with 5 cards
–
–
–
–
Look at 1st & 2nd / 1st and 3rd / 1st and 4th / 1st and 5th
Look at 2nd and 3rd / 2nd and 4th / 2nd and 5th
Look at 3rd and 4th / 3rd and 5th
Look at 4th and 5th
Swap
• One implementation detail is this – how do we
swap the values in 2 variables?
– For example, let’s say we want to swap x and y.
– What is wrong with this:
x = y;
y = x;
We need to do one more thing here!
“Swap” sort
• Here is how our sorting method would look in code:
for (i = 0; i < a.length; ++i)
for (j = i+1; j < a.length; ++j)
if (a[i] < a[j])
{
int temp = a[i];
a[i] = a[j];
a[j] = temp;
}
Sorting objects
• For our poker program, we need to sort an array
of objects, not an array of numbers.
– The difference is that we can’t use “<“ for cards!
– We need to compare some attribute of the cards.
– To tell if one card is “less” than another, should we
look at the denomination or the suit?
– The Card class will need an appropriate function to
compare itself with another card. For inspiration,
recall compareTo for strings.
Sorting cards
// c is the array of 5 cards in our poker hand
for (i = 0; i < c.length; ++i)
for (j = i+1; j < c.length; ++j)
if (c[i].compareTo(c[j]) < 0)
{
Card temp = c[i];
a[i] = a[j];
a[j] = temp;
}
CS 11 – April 18
• Poker game (handout)
– Deals and sorts cards
– Classifies the hand
– Let’s allow user to replace cards.
• Static function
– If you want Driver to have another “helper” function
besides main. Declare the function to be “static”.
– Static function means that you don’t need an object to
run it.
public static void sort(Card [ ] c)
CS 11 – April 21
• Debugging
– Add print statements at strategic places
– Eclipse has built-in debugger!
• Can step thru the program.
• Can look at values of all variables
• Breakpoints
– Automatic HTML documentation
– Can run at command line or within Eclipse.
• Enclosed by /** and */
• Can provide extra information by using “@ tags”
@param param_name description
@return describe what’s being returned
@deprecated
@author
easily see what documentation is missing or is hard to
understand.
CS 11 – April 22
• ArrayList built-in class
–
–
–
–
Contrast with arrays
Operations
Special handling for primitive types
Practical examples
See handout also.
Arrays
• Let’s review arrays!
–
–
–
–
One variable with many “cells”
Makes use of [ ] to index into the array
Can easily be extended to multiple dimensions
Card [] deck = new Card [52];
Month [] sched = new Month [12];
Student [] course = new Student [numStudents];
double [] temp = new double [365];
char [][] board = new char [8][8];
ArrayList features
–
–
–
–
First, we need to: import java.util.ArrayList
You don’t need to know size in advance.
Size is not fixed: it may grow or shrink as you want.
Has built-in functions to access information
•
•
•
•
size( )
get( )
set( )
– Only one-dimensional.
– Can only put objects into the list. Not primitive type.
• We can get around this obstacle. 
Examples
// Declaring and allocating space
ArrayList<Card> hand = new ArrayList<Card>();
ArrayList<Player> team = new ArrayList<Player>();
ArrayList<Student> s = new ArrayList<Student>();
Card c1 = new Card(27);
…
// getting and setting elements:
Card c2 = hand.get(4);
// akin to [4] for arrays
hand.set(7, c1);
// put card c1 in 8th position
Primitives?
• Technically, we can’t put “int” or any other
primitive type variables into an ArrayList.
• Workaround: Java provides Wrapper classes
–
–
–
–
Integer
Double
Character
etc.
• Even better news: When you try to put a
primitive value into ArrayList, it will automatically
be entered as an object.
Example
// Let’s have an ArrayList of integer values.
ArrayList<Integer> a = new ArrayList<Integer>();
// Let’s obtain the 3rd value from the list.
// To convert from Integer to int, use intValue.
// This is wrong: int thirdNum = a.get(2);
int thirdNum = a.get(2).intValue();
Wrapper classes
• Some notes on wrapper classes
– They are not often used except for ArrayLists.
– They have miscellaneous functions that manipulate
the binary representation, or express numbers in a
different base.
– Like String, they are located in java.lang, so you
never have to “import” them.
• Java arranges its classes into “packages” such as:
java.io._____
java.util._____
java.lang._____
(these are always imported automatically)
Why ArrayList
• You should use an ArrayList when you don’t
know how big an “array” should be in advance.
• Also nice when you want your “array” to grow
over time.
• Common scenario: file input
– Often you don’t know how big the file is!
Examples
– Read the server log, and count how many times each
user has logged in.
– Note: we don’t know how many “users” there are.
• Classroom scheduling
– We don’t know how many classrooms there are.
– Arrange each (buy/sell) transaction by company.
– We don’t know how many distinct companies there
are in the input.
CS 11 – April 23
Read a text file containing a server log. Keep
track of the number of times each user has
logged in.
• We don’t know how many users there are
• Begin with design
– We will need a “User” class
CS 11 – April 24
• New functionality for Login program
– (To practice “get” and “set” with ArrayList.)
– Make output formatting more attractive.
• Can be done in toString()
• In this case, more straightforward to do it in main()
– Find total number of logins
– Sort the ArrayList so most active users appear first.
CS 11 – April 25
• Third version of Login program
– Handout
– Review sort.
– Search ArrayList for a specific user.
• Adapt strategy to other problems.
– Ex. Stock portfolio
CS 11 – April 28
• Exception handling
– “Exception” is another word for run-time error
– Types of exceptions
– Two ways to protect yourself
• If statement √
• Java statements: try and catch
Exceptions
• Something that goes wrong during program
execution causing it to abort.
• Examples
–
–
–
–
–
FileNotFoundException
NumberFormatException
EOFException
IndexOutOfBoundsException
NoSuchElementException
• Some exceptions are so important, that Java
wants you to handle them!
Plan for exceptions
• Protect your program from abnormal termination
– Beware of code that might raise some exception
• Testing can reveal potential problems. 
•
•
•
•
Opening a file: what if it doesn’t exist?
Reading an integer: what if it’s something else?
Read next input from file: what if nothing left?
Accessing some element from an array,
ArrayList, or String: have I gone too far?
Handling exceptions
• There are 2 ways to “handle” exceptions
–  Use an if statement. For example, replace:
if (s.charAt(index) == ‘a’)
with this:
if (index < s.length() &&
index >= 0 &&
s.charAt(index) == ‘a’)
–  Use the try and catch statements. These are
specially designed for handling exceptions.
try / catch
• The keywords try and catch are used to handle
exceptions. Here is the general format.
try
{
// potentially exceptional code
}
catch(ExceptionType e)
{
// what we should do if Exception occurs
}
// continue with rest of program
String example
• Suppose I want to set found to true if s.charAt(index)
is ‘a’. But I don’t know the value of index, and it could be
out of bounds.
try
{
if (s.charAt(index) == ‘a’)
found = true;
}
catch(StringIndexOutOfBounds e)
{
System.out.printf(“Uh-oh: string too short.\n”);
}
No such file
• More common example: opening a file.
Scanner in = null;
try
{
in = new Scanner(new
FileInputStream(inFileName));
}
catch(FileNotFoundException e)
{
System.out.printf(“File doesn’t exist.\n”);
}
// If in is not null, we can read from file 
// NOTE that ‘in’ had to be declared before try.
// Should enclose this code in a loop to re-enter.
Error checking
• Here is a general approach.
needInput = true;
while (needInput)
{
Try block: get the input
Catch exception, print error and continue.
After catch block, set needInput to false.
}
Function “throws…”
• You probably remember in File I/O that we used to put
“throws FileNotFoundException” at end of function
declaration.
public Deck() throws FileNotFoundException
• This means that we are not handling the exception.
– “Passing the buck”
– It will be handled by whatever function called me.
– If main() says it’s throwing an exception, it will then be handled
by the Java system.
• If you are handling the exception, you no longer need to
say the function throws the exception.
CS 11 – April 29
• This middle unit of the course has focused on
making our solutions more productive. What
remains:
– Exception handling example
• Passing the buck, have calling environment handle exception
• See handout
– Conditional operator
• Short cut to doing an “if” condition
– Character processing
• Applying arithmetic on characters
• Examples: cryptography, Wheel of Fortune game.
Conditional operator
• How can we fix this?
• We could use an if statement, but a more concise way to
handle the problem is with a special operator?
:
• It’s an expression often used for printing out or for
assigning.
• General format:
<condition> ? <value if true> : <value if false>
Examples
• Singular/plural
System.out.printf(“I found %d %s\n”, count,
• Absolute value of the difference: | x – y |
abs = x-y >= 0 ? x-y : y-x;
• Overtime pay
// Let’s work this one out ourselves.
// The condition is hours > 40...
More on char
• Briefly mentioned before: char is an “integral” type
• We can use + and – on characters.
• Not only that, each character value has a numerical
representation!
• Important for cryptography
– Example: add 3 to every letter in a word:
“hungry dog” could be encoded as “kxqjub grj”
– Pretty straightforward to write a loop to accomplish this.
CS 11 – April 30
• Case study: hangman game
– Driver: simple loop where user makes guesses until
game is over.
– Several attributes such as:
•
•
•
•
Display: show what part of the word is known to player
Remember previous guesses
CS 11 – May 1
Finish hangman game
– Play() function
• How to tell if user already guessed this letter?
– Is everything in the right order?
• What kind of error message to report if the user makes the
same wrong guess twice?
– Constructor: change answer to random word
• Better to isolate this in a new function setAnswer()
• Select random word from dictionary.
List of topics
• Random numbers
• Review of operators,
precedence, associativity
• Different kinds of loops
• Break and continue
• Nested loops
• 2-D arrays
• Switch statement
• Sorting an array
• Using debugger and
• ArrayList
• Exceptions
• Conditional operator
• Character processing
• Case studies
– Poker
– Hangman
CS 11 – May 5
• What’s left?
– Tokenizing
– Creating images
– Useful tricks (java-archive, persistent objects)
– Designing larger programs
– Applets and GUIs 
Tokenizing
• Chopping a long string into pieces (tokens).
• Examples:
– “1, 2, 3, 4, go”  “1” , “2” , “3” , “4” , “go”
– “9:30-12:45”  “9” , “30” , “12” , “45”
• Three ways to do it
– Scanner class: next( )
– StringTokenizer class: nextToken( )
– String class: split( )
Using Scanner
• The easiest way to break up string into tokens. √
String s = “entrée 8.95 dessert 2.50”;
Scanner scan = new Scanner(s);
String token1 = scan.next();
String token2 = scan.next();
// ETC.
// “entrée”
// “8.95”
• Assumes that tokens are only separated by spaces.
• Difficult to use other characters as delimiters.
StringTokenizer
• Usually the easiest way to tokenize in the
general case. 
– Import java.util.StringTokenizer
– Call the constructor
• Tell it what string you want to tokenize,
• And also what characters serve as delimiters.
– call nextToken( ) or hasNextToken( ) as appropriate.
String s = “1, 2, 3, 4, go”;
StringTokenizer tok = new StringTokenizer(s, “, “);
String token1 = tok.nextToken();
Token loop
• Often we want to look at all the tokens in a
string. We use a while loop.
…
while (tok.hasMoreTokens())
{
String token = tok.nextToken();
// do whatever you want to this token
}
String split
• More difficult to use, but can handle any case.
• Example: tokenizing pairs of numbers
– “1,2, 5,8, 3,9, 7,0”  “1,2” , “5,8” , “3,9” , “7,0”
– Tokenizing these pairs using StringTokenizer would
be difficult, because some commas are delimiters, but
some are not!
• String class has a split function.
– Parameter tells it what the delimiter pattern is.
– Returns an array of tokens (Strings).
Split examples
• Separate on hyphen only.
String s “moo-goo-gai-pan”;
String [] tok = s.split(“-”);
The array tok now contains: “moo”, “goo”, “gai”, “pan”
• Separate on double hyphen.
String s = “moo-goo--gai-pan”;
String tok = s.split(“--”);
The array tok contains: “moo-goo”, “gai-pan”
• Unlike StringTokenizer, split assumes the delimiter fits
some pattern, called a regular expression.
examples
• What is the pattern for:
“1,2, 5,8, 3,9, 7,0” ?
What separates these tokens is a comma followed by a
space.
• split( ) is a little more difficult because of the notation for
special characters like spaces and certain punctuation.
– For space, we need to use \\s+ or \\s*
String s = “1,2,
5,8,
3,9,
7,0”;
String [] tok = s.split(“,\\s+”);
Today’s lab
• Work in groups of 2 or 3 people.
• At 2:00, meet in room 204 across from usual lab
room.
– 30 minutes designing solution to a problem.
• Around 2:30, we go to computer room.
– 90 minutes implementation.
• Have fun!
CS 11 – May 6
• Creating images as output
– Create image object from BufferedImage class
– Color each pixel (usually nested loop)
– Write output to .png file
• Example: French flag
CS 11 – May 7
• Image is 2-d arrangement of pixels, but not quite
the same as 2-d array.
– “row” and “column” might be confusing
– Best to think of pixels in terms of x and y.
• Pixel colors determined by RGB system
• Example flags
– Poland
– Czech republic: slanted lines and slope
– UK: drawing stripes
CS 11 – May 8
• Yesterday we colored pixels according to RGB
– 8 bit numbers each for red, green and blue.
• Today, let’s play around with some binary.
• Java has several “bitwise” operators.
– Shift operators move bits left or right.
– Logical operators inspect or change individual bits.
– Often used in cryptography.
• First, we should look at binary numbers.
Binary
• Binary means “base 2”. Binary numbers consist
solely of 0s and 1s.
• In Java, integers occupy 32 bits. We’ll write
down just the ones we need.
• Place value system
– Rightmost bit corresponds to 1.
– As you go left, the bit positions get heavier, and each
one is a power of 2.
– Example: The number 101001 is 32+8+1 = 41.
Shift operations
• Java allows us to shift bits left or right. We just need to
specify how far we want to go.
<< means shift left
>> means shift right
• Examples. Suppose n equals 26 (11010 in binary).
(n << 1) becomes
110100
(n << 2) becomes 1101000
(n << 3) becomes 11010000
(n >> 1) becomes
1101
(n >> 2) becomes
110 (oops, we lost a 1 !)
More on shift
• Computers love shift operations because they
are a lot faster than multiply/divide.
• Each time you shift left by 1, you double the
value of the number.
– Ex. To multiply something by 64, just shift it left by 6.
y = 64 * x;
y = x << 6;
• This might be easier to see if you take a look at
these binary numbers: 101, 1010, 101000,
1010000, etc.
Bitwise logical ops
• Java has 4 logical
operators that manipulate
bits.
& means “and”
| means “or”
^ means “exclusive or”
~ means “not”
Don’t confuse & with && or
| with ||.
X
Y
X&Y X|Y X^Y
1
1
1
1
0
1
0
0
1
1
0
1
0
1
1
0
0
0
0
0
How they work
101011
& 011001
--------------001001
101011
| 011001
--------------111011
101011
^ 011001
--------------110010
The ~ operator is easy. It just inverts all the bits:
~(101001) equals:
010110
Printing binary!
• Wwe are almost ready to teach Java how to print
binary numbers!
• We have to look at each bit one at a time, see if
it’s a 1 or a 0, and then print that digit.
• It’s customary to number the bit positions from
31 on the left to 0 on the right.
for (n = 31; n >= 0; --n)
if this bit position is a “1”, print 1
else print “0”.
Problem
• How do we ask Java if a particular bit (or set of bits) is
set to 1?
• It turns out we can “AND” the bit in question with 1, and
see if the result is zero or nonzero.
• Example: the number 13 (1101).
(The leftmost 28 bits are all 0’s – let’s ignore them. )
1101: AND with 1000 to obtain nonzero result 1000
1101: AND with 0100 to obtain nonzero result 0100
1101: AND with 0010 to obtain zero
1101: AND with 0001 to obtain nonzero result 0001
Print binary
Here’s how to do it:
value = 278; // or anything we want
for (n = 31; n >= 0; --n)
{
if ((value & mask) != 0)
System.out.printf(“1”);
else
System.out.printf(“0”);
}
System.out.printf(“\n”);
CS 11 – May 12
• Software design
– Class relationships
– Managing a larger program
• Interface – helpful tool for design
• Two kinds of relationships classes can have:
– Aggregation: “has a”
– Inheritance: “is a”
A big class
• Big classes tend to have many attributes.
• We could easily come up with 20 attributes for a
House class! Too many to remember.
• With many attributes, helpful to organize into
“levels of abstraction”. In other words, a
bureacracy.
– House attributes may be grouped by: Interior,
Exterior, Furnishings
– House has a Bathroom, Bathroom has a sink.
– House is an attribute of even larger classes!
Aggregation
• “has a” relationship between classes. Very
common.
• Happens anytime an attribute is itself a class.
But the interesting cases are where we have
array or ArrayList of objects:
– Deck has Cards
– Team has Players
– (At Olympics) Country has Teams
Example
• Imagine registration for the Olympics. How would we
maintain this data? (When to create/insert objects).
Xiaobing Zhang, China, Luge
Jing Chen, China, Luge
Minghui Yang, China, Alpine Skiing
Klaus Becker, Austria, Luge
Karl Fischer, Austria, Bobsled
Johannes Korvald, Norway, Alpine Skiing
Jens Schaffer, Germany, Luge
Gertrude Bosch, Austria, Alpine Skiing
Emma Prets, Austria, Bobsled
Interfaces
• “Interface” is a big word in OO programming
• Idea is simple: it’s a “to-do” list of all the
functions we want to implement for our class.
– Theoretically, you could implement a class in 2
different ways. For example once with an array and
once with an ArrayList. Or using different methods of
encryption!
• An interface is a separate Java file. Declare, but
do not implement functions.
• The class says it “implements” the interface.
– Compiler will check if all functions are present.
CS 11 – May 13
Aids to large programming
• Work on a team!
• Look for class relationships
– Aggregation: one class contained in another √
– Interface: classes sharing common functionality
– Inheritance: one class is a more specialized version
of an existing one
Interface
• To-do list of functions we want to implement
• Useful when
– there are multiple ways to implement a class
– Classes have essentially the same functionality
• Examples
–
–
–
–
Stock: we want to buy, sell, look up price
Encryption: we want to encrypt and decrypt
BoardGame: we want to insert tokens, check for win
2D shape: perimeter and area
Nuts and bolts
• An interface is defined in its own Java file.
public interface GameInterface { … }
• Only function declarations. No attributes.
• When you are ready to write the class, say that
you are “implementing” the interface.
public class Pente implements GameInterface
public class Othello implements GameInterface
• Compiler will tell you if something is missing!
Inheritance
• Design technique: create a class based on an
existing one. You don’t have to start from
scratch.
• Two reasons to use inheritance
– You have/find a class you like, but wish it could do
more. For example, the built-in Random class is nice,
but it can’t generate random characters and words!
– You want to make a class more specific.
• Rectangle, Cube and Sphere are more specific versions of
Shape
• Fish, Reptile, Bird are more specific versions of Animal
• Book, Magazine are more specific than Publication
“Zoo” example
• I want to write a program that simulates animals
in a zoo. Feed, weigh and exercise the animals.
• We’ll use the following classes: Animal, Fish,
Reptile, Bird, Penguin, Snake
• What kind of inheritance do we have here?
CS 11 – May 14
• Inheritance
– Important class relationship
– Helps us create new classes from existing ones
– Not to be confused with Aggregation, Interface
– Handout: “zoo” program shows how to use
inheritance
Examples
Animal
Fish
Reptile
Snake
Room
Bird
Bedroom
Kitchen
Penguin
Vehicle
Car
Tank
Be careful
• Inheritance: we want a class that is a
specialized version of something else.
– Ex. A rabbit is a special kind of animal.
• Don’t confuse with aggregation.
– A deck of cards is not a special kind of card, or vice
versa.
– A player is not a special kind of team.
• Don’t confuse with Interface.
– Connect 4 is not a special kind of Tic-Tac-Toe. These
games just happen to have similar operations.
Concepts
• For example, Vehicle, Car and Tank
• Relationship
– Vehicle is the “super” class. Car and Tank are “sub”
classes of Vehicle.
– We say “Car extends Vehicle”, etc.
• First, we want to create a Vehicle.
– Has its own attributes, operations
• Cars and Tanks are specialized vehicles.
– Have additional attributes & operations that go
beyond the basic vehicle.
– Sub classes may override anything defined in super
class.
Design 
Vehicle class
weight
fuelType
capacity
(constructor)
cruisingRange()
fillErUp()
drive()
changeOil()
Inheritance
simplifies design of
subclasses.
Car class
air bag
(constructor)
wash()
Tank class
weapons
(constructor)
fire()
Some details
• We want superclass to share its attributes with
its subclasses:
– make them “protected” instead of “private”
• We want subclass constructor to call superclass
constructor first.
– For default constructors, this happens automatically
. Otherwise, we have to call “super(…)” ourselves.
• Subclasses may override superclass function
– We may want to re-define drive() or toString().
No confusion
• To override a function means to write a function
with the same name in the subclass.
Tank t = new Tank();
t.drive();
System.out.printf(“%s\n”, t.toString());
• Which drive() and toString() are being called?
– First, look in Tank class to see if it’s implemented
there.
– If not, go “up the chain of command.”
Object class
• It turns out that some functions are extremely
common:
– toString()
– equals()
• For this reason, Java has a built-in class called
Object. All classes automatically extend Object.
You don’t have to say “extends Object” yourself.
– This means that if you don’t override toString() or
equals(), you’ll automatically use Object’s version of
them, which is usually not what you want!
Zoo example
• Interactive program highlighting inheritance
concepts.
– Constructors calling (superclass) constructors.
– Overriding functions
– The keyword super
• Allows us to call a function/constructor in parent class.
– The keyword instanceof
• For example, you can ask an Animal if it happens to be a
bird, or ask a Vehicle to see if it’s a Tank.
CS 11 – May 15
• Inheritance
– Zoo example
– polymorphism
– instanceof (keyword in Java)
• GUIs 
– JOptionPane built-in class
– applets
Zoo program
• Illustrates inheritance
– Subclass “extends” superclass √
– Overriding superclass functions… or not √
– Constructors calling superclass constructors √
• Animal’s exercise() function
– Rather than override this function in every class (like
feed()), different approach here. One function in
Animal.
– But Animal needs to be sure it “exercises” itself in the
appropriate way. Use instanceof to find out what
kind of animal I am.
Polymorphism
• Sometimes we want to create an object, but at first
we don’t want to get specific.
– You want a car, but not sure what make/style.
– You want to open an account, but not sure of options.
– Conceive a child, but we don’t know if it’s a boy or girl.
Animal creature = new Animal();
creature = new Dwarf();
...
...
// general
// specific
// specific
GUIs
• GUI = graphical user interface
• Some features
– Windows on screen, may be divided into panels/tabs
– “labels” containing announcements or other text for
user
– Text boxes for text input
– Buttons
– Ability to respond to mouse motion, clicks, drags.
• Too many details to memorize!
– Rely on online documentation.
Types of GUIs
• JOptionPane class
– simplest GUI functionality
– showInputDialog() – prompt the user for input
– showMessageDialog() – for output
• Applet
– Designed to run inside browser or other “applet
viewer” program
– No main() function.
• Stand-alone application
– We do this in CS 12!
Applet
• “extends” Applet class
• We write 2 functions
– init() which is called from browser. This is called just
once at the beginning. Initialize variables here, if any.
– paint() is called every time the window is refreshed.
• This is where we can draw geometric shapes
• Geometric objects
• Use many built-in classes!
• To run applet, need to write a little HTML .
<applet code="FirstApplet.class" width="300"
height="300"></applet>
CS 11 – May 16
• Applets
– Designed to display window in a Web browser.
– Simpler to create than a full GUI application.
• Examples
– FirstApplet: geometric shapes
– Mouse applets: respond to “events”
paint()
• Anything you want shown in an applet needs to
be implemented in paint().
• Use built-in graphics object, which I’ve called g2.
Anytime you’re ready to draw something, you
call: draw(), fill(), setColor()
• Rectangle built-in class
– Need to know position of top left corner
– Need to know width and height of rectangle.
• Can also draw: Circles, Lines, Polygons
Interactive
• Applets aren’t too interesting unless the user can
interact with them… using the mouse!
• In addition to init() and paint(), we also need to
implement a MouseListener.
– Waits for somebody to move or click the mouse.
– As soon as that event occurs, we automatically go
into appropriate mouse listener function.
• MouseListener is a built-in interface
– 5 required functions (e.g. mousePressed), even
though we may not use them all.
– We need a class that “implements” this interface.
CS 11 – May 19
• Mouse Applets
– Respond to clicking: repaint (redraw) the window
– Inner class to detect input
• Implements MouseListener interface
• Event driven
• mousePressed() is only called when someone presses the
mouse.
• It doesn’t have to be an inner class, but often convenient to
do so.
– Examples
Applet structure
Attributes help us
determine what to
to draw.
Executed once, at
beginning
Executed when
there is a mouse
event.
Executed when
window
refreshed.
My Applet class:
attributes
init():
Create objects to draw
Start the listener
Listener class:
Grab x,y values
call repaint()
paint(): Listener class:
call repaint()
Mouse Applet 3
• 64 Rectangle objects arranged 8x8.
• Each box is 35x35 pixels.
• Only responds to mousePressed
• What happens when we click somewhere?
– mousePressed(): we find (x,y) coordinates
– Compute corresponding row and col values
– paint(): fill in that single square blue as we draw the
entire board.
Mouse Applet 4
• Same 8x8 array “box” of Rectangles to draw
• 8x8 array of int storing who is occupying “board”
0 = position is empty
1 = occupied by Blue player
2 = occupied by Red player
• Keep track of how many moves, so we can
alternate players.
– If user clicks already-occupied square, disregard
move.
• paint() fills in squares: correspondence between
board[ ] [ ] and box[ ] [ ].
CS 16 – May 20
Some useful tools
• Command line arguments
• Web robot
Command line args
• Have you noticed how main is declared?
public static void main (String [] args)
• We can pass arguments as we run the program!
• Java creates an array of Strings based on what
is typed after “java Driver” (or whatever program
is called)
• For example, if we run a program as:
java Driver ice cream cone 4 you
args is now an array with 5 strings.
Example
• We can write a very simple program that can
allow someone to add several numbers on the
command line:
java Add 7 2 6 -3
• With exception handling, we can even ignore
non-integer values if we wish.
Time
• Java has a built-in function
System.currentTimeMillis()
that returns the number of milliseconds elapsed
since the beginning of 1970.
• Big number! Returns long.
• Can use to time a portion of code
t1 = check the time
do something
t2 = check the time
elapsed time = t2 – t1
Example
• I’m curious how long it takes for Java to pick a
random number.
• But generating 1 random number takes far less
than 1 ms!
– Use a loop to generate lots of random numbers.
– “Dual loop” method.
CS 11 – May 21
Web Robot
• Besides GUIs, one of the great features of Java
is its ability to surf the Web for you automatically!
• Create a URL object.
• Open a URL, and read from the Web page as
though it’s a text file.
• Example: reading current stock prices!
```