cs 11 – aug. 27
Post on 21-Jan-2016
41 Views
Preview:
DESCRIPTION
TRANSCRIPT
CS 11 – Aug. 27
• Course overview– Computers & computer science– Nature of problem solving
• Next, we’ll continue with– What software looks like– Problem-solving procedure
Note: Important terminology highlighted in yellow.
What is a computer?
• Machine that stores and processes information
• With memory, machine can be programmed. Memory stores software and other files.
• Information inside memory is all in binary!
• CPU’s job is to obey instructions from a program.
+ * – / %√ Σ
CPUMemory
file
file
file
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 can help you automate the calculations.
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.
CS 11 – Aug. 28
Overview, continued
• “recipe” analogy• Languages for the computer• What does software look like?• Problem-solving procedure
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 menu for choices.
if (have all ingredients), make Shepherd’s pie.
if (no potatoes), just make soup instead.
if (no veggies), make hamburger.
if (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 well-defined structure, such as listing the ingredients and steps for input, calculations and output.
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
Javaprogram
Javacompiler
Bytecode
Can execute in CPU.
Compiler reads your program.
It checks for simple mistakes, and then translates your code into binary.
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
solution for a human reader.– 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.)
– Add two numbers and report answer.
(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.
Lab
• Let’s practice running simple programs on the computer.
• Make sure you have an account, and you know your password.
• Follow directions on lab handout.
CS 11 – Aug. 29
• How to do I/O
• Problem-solving procedure.
• You can find class notes on
cs.furman.edu/~chealy/cs11
Scanner
• When reading input, we can use the built-in Scanner. (See BasicProgram handout.)
Scanner kbd = new Scanner(System.in);
Says that we want to create a scanner, based on the keyboard input, which Java calls System.in.
int input = kbd.nextInt();
• When you want to read an integer, call the function nextInt();
• Again, don’t worry about every single detail at this point.
printf
• Formatted printing• Designed to print a string in quotes, possibly
with extra information such as variables.System.out.printf(“Hello.\n”);
System.out.printf(“answer = %d\n”, answer);
• 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);
Problem solving
• Need to have a plan!• Often a bad idea to rush to keyboard and
start typing code.
• Problem solving procedure:
(See handout)– design– implementation
Advice
• To learn problem-solving, must practice– Look at examples ( This is not a theory course )– Use built-in features of Java to simplify 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.
Advice (2)
• 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 – Sept. 3
Fundamental ideas
• Practice the problem-solving procedure• Statements• Variables: names and types• More about Scanner for input
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 27 and 42 cents.
• In our solution, we’ll need– Variables to store numbers.– Format the output so it looks like money.
• Once finished, we can enhance solution.– Special message if over $10.
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 Purpose # bytes range
byte Integer 1 -128 to 127
short Integer 2 +/- 32k
int Integer 4 +/- 2 billion
long Integer 8 +/- 1019
float Real # 4 +/- 1038
double Real # 8 +/- 10308
char single char. 2 Unicode
boolean true/false 1 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.
Scanner (2)
• Let’s apply what we know– We can declare and use variables of various types.– The Scanner can get input of various types.
• ExamplesString name = kbd.next();double length = kbd.nextDouble();int size = kbd.nextInt();
• Pay close attention to the types. They must agree. For example, the following is bad:
double height = kbd.nextInt();
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
Next Example: F/C
• Design a program that allows the user to convert from Fahrenheit to Celsius, or the other way around.
Do you want F C or C F
?
DoF C
DoC F
CS 11 – Sept. 4
• Review what we know– Problem solving procedure– Basic parts to a program– Statements & variables
• If-statement– Comparisons: < > == etc.
If-statement
• Use to ask a questionif (amt < 10.00) if (num < 0)
no credit card 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.5xif (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
?
DoF C
DoC 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 structure of our program ahead of time. (WordPad)
– Implementation phase – • Open Eclipse, create “project”, telling it where your
source files are.• Compile and run whenever you like.• Finish typing code here.
CS 11 – Sept. 5
• Ideas from lab– FC: type of an expression & conversions– Paint: intermediate calculations
• Using / and %• More about the if-statement
– Leap year example– Testing multiple conditions
• Next week: String data type– Let’s have a tutorial on Tuesday, room 200-F
Expression type
• Sometimes we need to convert integer expression into real numbers.– In FC program, beware of typing 9/5 and 5/9 !
• 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
• Extra parens are ok, but don’t type: (double) (a / b) !
• Ex. Converting win-loss record % wins.
Paint calculations…
• We used intermediate calculations for area of room, gallons of paint… finally cost of paint.– Don’t write just one “silver bullet” formula.
• 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.
• Note about the lab: We didn’t do any error checking of input. We’ll learn about this later.
/ 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
Review of if
• if statements look like this:
if (question) if (question)
statement {
block of statement(s)
}
• The “question” is usually a comparison as inif (num % 2 == 0) ...
• It’s optional to have an else portion underneath
Leap years
• Remainders can help – Simple approach: if (year % 4 == 0) …
– Full definition: if the year ends in 00, it must be divisible by 400, otherwise it just needs to be divisible by 4
– To write as if-statement, we 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. ...
• How would we do these?– Testing for positive, negative or zero.– Converting numerical grade to letter grade
Answers
if (value > 0)
// do positive case
else if (value < 0)
// do negative case
else
// at this point, we
// know it’s zero!
if (grade >= 90)
letter = 'A';
else if (grade >= 80)
letter = 'B';
else if (grade >= 70)
letter = 'C';
else if (grade >= 60)
letter = 'D';
else
letter = 'F';
CS 11 – Sept. 8
String data type• Not a primitive type: it’s a “class”
– Additional feature to the language.
• Representation• Useful operations, for example:
– What is the 7th letter?– Searching for a word in some text– Checking a password– Given 2 names, can we tell which one would appear
first alphabetically?
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
• ExamplesString s = “Hello”;s.length() would return the value 5s.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 = kbd.next();String last = kbd.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"
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”; s1 = “fish”;
String s2 = “cow”; s2 = “files”;
int diff = s1.compareTo(s2); diff = s1.compareTo(s2);
Index 0 1 2
s1 = c a t
s2 = c o w
subtract 0 -14
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.
Index 0 1 2 3 4
s1 = f i s h
s2 = f i l e s
subtract 0 0 7
String handout
• StringFun.java features these String functions:– charAt– equals and equalsIgnoreCase– compareTo– startsWith and endsWith– length– indexOf and lastIndexOf– substring– replace
CS 11 – Sept. 10
• 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”; s1 = “fish”;
String s2 = “cow”; s2 = “files”;
int diff = s1.compareTo(s2); diff = s1.compareTo(s2);
Index 0 1 2
s1 = c a t
s2 = c o w
subtract 0 -14
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.
Index 0 1 2 3 4
s1 = f i s h
s2 = f i l e s
subtract 0 0 7
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 first = kbd.nextInt();
int second = kbd.nextInt();
int third = kbd.nextInt();
…
int 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.
CS 11 – Sept. 11
• Review loops (while-statement)– Ex. How to add or count.– Common mistakes to avoid– Examples using strings.
Add 5
// Now we’re ready to read 5 numbers and add them.
// 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)
{
int newNumber = kbd.nextInt();
sum = sum + newNumber;
count = count + 1;
}
System.out.printf("The sum is %d\n", sum);
This solutionscales well forlarger input.
Common mistakes
• Initially falsenum = 1;while (num > 10) …
• Infinite loop !num = 1;while (num <= 10)
{ System.out.printf(“%d\n”, num);}
• Off by onenum = 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 example
• 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.
String word = "railroad";
int index = 0;
while (index < word.length())
{
// grab character from the word
// if it’s an “E” then add 1 to our count.
}
Counting E’s
String word = "railroad";
int index = 0;
int count = 0;
while (index < word.length())
{
char letter = word.charAt(index);
if (letter == ‘E’ || letter == ‘e’)
count = count + 1;
index = index + 1;
}
Example (2)
• Reverse a word.– Again, need charAt to obtain 1 letter at a time.– Need to use + to help us build a new word.
String oldWord = "balloon";
String newWord = "";
// How do we build the new word?
// Each letter from oldWord gets appended to newWord
“” “n” “no” “noo” “nool” …
Reverse
String oldWord = "balloon";
String newWord = "";
// Start at the end of the word.
index = oldWord.length() – 1;
while(index >= 0)
{
char letter = oldWord.charAt(index);
newWord = newWord + letter;
}
CS 11 – Sept. 12
• Lab recap
• File I/O– Similar to regular I/O with Scanner & printf, except we
need more “special ingredients”.– File output: use PrintStream– File input: use FileInputStream– Possibility of something wrong with file:
FileNotFoundException
Counting E’s (review)// CORRECT VERSIONString s = "railroad";int index = 0;int count = 0;
while (index < s.length()){ char letter =
s.charAt(index); if (letter == ‘e’) { count = count + 1; } index = index + 1;}
// WHAT’S WRONG HERE???String s = "railroad";int index = 0;int count = 0;
char letter = s.charAt(index);
while (index < s.length()){ if (letter == ‘e’) { count = count + 1; } index = index + 1;}
Counting E’s (review)// CORRECT VERSIONString s = "railroad";int index = 0;int count = 0;
while (index < s.length()){ char letter =
s.charAt(index); if (letter == ‘e’) { count = count + 1; } index = index + 1;}
// WHAT’S WRONG HERE???String s = "railroad";int index = 0;int count = 0;
while (index < s.length()){ char letter =
s.charAt(index);
if (letter == ‘e’) { count = count + 1; index = index + 1; }}
Why File I/O?
• 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 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.)
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
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 and/or read from multiple files.– Doesn’t happen often.
CS 11 – Sept. 15
• Finish file I/O examples– Win/loss program needs to read String and int
• Error checking of input
• Sometimes we also need a lot of similar variables.– An array is more efficient.– Like a string, but may contain #’s rather than
characters.
Int/String conversion
• Converting String to int– Use the function Integer.parseInt( )
String s = "456";
int value = Integer.parseInt(s);– If string has extra spaces: use trim( )
s = "1234 ";
value = Integer.parseInt(s.trim());
• Converting int to String– Concatenate the number onto an empty string
int value = 789;
String s = "" + value;
Error checking
• Program is hungry for input, and user might not enter the right “food”.
• Handle with a loop and boolean variable…
needInput = trueAs 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)
{
System.out.printf("Please enter positive int:");
value = kbd.nextInt();
if (value > 0)
needInput = false;
else
System.out.printf("Sorry, your input is " +
"invalid. Try again.\n");
}
Recap
• 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.)– Could read file again– 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 };
Array loop
• We almost always use a loop with an array.int index = 0;
while (index < 100)
{
score[index] = sc.nextInt();
index = index + 1;
}
• Accessing individual cells in array is analogous to individual char’s in a string.– Instead of stringName.charAt(location) we use
arrayName[location]
Examples
For an array of numbers, how can we …?
• 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.
CS 11 – Sept. 17
• Revisit arrays …– We often use loops with arrays– Array elements are numbered from 0 to a.length – 1– How to search for something
• 3 kinds of programming errors
• Practice
Array operations
• Initialize, input, calc, output √– Handout showing loops
• 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;
index = index + 1;
}
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.)
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.
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 – Sept. 19
• Practice problem solving. Consider:– Variables you need. E.g. Do we need array?– What kind of I/O we need– Do we need to loop?– Choices to make– The order in which things should be done
• I’m collecting a list of “Java skills”:http://cs.furman.edu/~chealy/cs11/skills.html
Fibonacci
• 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 shouldstrive to have solutions
that are easy to understand
If you have a “clever”solution, please writea careful comment
explaining it.
Better Fibonacci
• A more straightforward way to generate Fibonacci numbers is to store them in an array.
• This way, it’s easier to refer to earlier values, because you don’t have to throw away anything.
int [] fib = new int [25];
fib[0] = 1;
fib[1] = 1;
int i = 2;
while (i < 25)
{
fib[i] = fib[i-1] +
fib[i-2];
i = i + 1;
}
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.
√ 5 :
1.000
3.000
2.333
2.238
2.236
To do absolute value, use Math.abs( ).
CS 11 – Sept. 22
• 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
}
Functions
• Encapsulate a set of calculations• Usually ask something about an object• Parameters (how many, what type)
• Return value (what type)
findMax( )
7
4
8
8
String examples
String s = “ice cream cone”;
• A string object can call its own functions.
length
charAt
equals
substring
14
4 ‘c’
“tree” false
5
9“ream”
Triangle functions
• This example is rather simple. Nearly all the functions:– Need no parameters, because they are questions
about the triangle itself.– Returned a boolean value, because they were
answering yes/no questions.
• 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 – Sept. 24
Object-oriented strategy• Overview √
– Solutions separated into 2 source files
• Function concepts √– Parameters– Return value
• Designing a class– Attributes and operations
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
{
private double radius; …
Constructor
• This is a function that initializes the attributes.– Usually we initialize based on parameters being
passed from the main() function. We might want 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!– getBalance– writeCheck – transferTo
• For each function, it helps to ask:– Does it need any parameters?– Does it change an attribute value?– Will it return a value?
CS 11 – Sept. 25
• Practice with creating classes
• Class definition file (e.g. House.java) – defines attributes and operations of a class
• Driver.java – contains the main() function, uses functionality of the class
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...
CS 11 – Sept. 26
• Object-oriented approach– Organize our solution into 2 files √– Constructors– Using constants
• Examples of class design– Triangle, Account, House examples √– Road trip: Cost per mile of driving a car.– Calculate amount of time to fill a pool.
• Sometimes, we want to return new object– Adding amounts of time, such as 6h13 + 2h27
Constructors
• There are 3 kinds of constructors, depending on what parameters we want to pass.
– Initial-value: parameters are used for the initializationRoom 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 objectRoom 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;
}
You can also refer to your own attributes as this._________,for example this.length rather than simply length.
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, is Math.PI
Design practice
• Organize solution into 2 files– Driver.java should be concise– Class definition file should contain details
1.Road trip: cost per mile– Figure out what the big noun is…– Its attributes and operations
2.How long to fill a swimming pool.
3.Adding 2 amounts of time (e.g. 6h13 + 2h27)
4.Working with fractions
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;
}
Time t = new Time(totalHour, totalMin);
return t;
}
CS 11 – Sept. 29
• Example: Fraction class– Illustrates “this” and returning a new object
• Array of objects – Fortunately, arrays can handle objects just as easily
as primitive-type variables.– Example: deck of cards!
• Array as an attribute– A month consists of many days
Fraction class
• Attributes– Numerator– Denominator
• Operations– Constructors– Add– 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 OTPIT 46 26 7
MON 44 25 10
CAR 42 31 6
NJ 43 28 7
Design
• How would we create a “Card” class?– Attributes: denom, suit– Operations: constructors, getDenom, getSuit,
toString public String toString() { return denom + " of " + suit; }
• Team class– Attributes: name, wins, losses, otl– Operations: constructors, “get” functions, toString
CS 11 – Oct. 1
• Announcements
• Example: 1 month’s climate data– Array of objects
– Convenient to organize into 3 source files.• We’ll define a Month class and a Day class
– 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
Upcoming
• Homework #1 – climate classification– Given a city’s monthly temp & precip, tell if it’s a
desert, tundra, tropical, etc.– Design due on Tuesday, Oct. 7– Program due on Wednesday, Oct. 15
• Guest speaker – Friday, Oct. 10– Sean O’Keefe, former director of NASA– location TBA
• Test #1 – Monday, Oct. 13
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 array: read file.• The “find” functions
• Day– Attributes
• High temp• Low temp• Rain
Monthly climate
• The most interesting part of the program is the Month class.
• Constructor reads input file.– 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 – Oct. 6
• Thinking about a toaster oven… • Friday’s talk in Room 126, Plyler Hall.
Practice with shopping list case study:
Read a shopping list from a text file. Print it out in attractive format, and compute total.
• We create 2 new data types (classes).• Another case of having an attribute that is an array of
objects. • If we had time, we could do more:
– Sales tax; Only print out items over $1
Design
ShoppingList• Array of Items
• Constructor– Read from file– Create items array
• findTotal( )• toString( )
Item• Name and price
• Constructor• getPrice( )• toString( )
Implementation hints
• Both toString’s need to format output like printf would. We use: String.format( )
• ShoppingList’s toString() needs to show a whole list, so we need a loop.
• findTotal()– We already know how to add up elements of an array,
but this time it’s a little different. We’re not adding the items, but rather their prices.
CS 11 – Oct. 8
• Finish shopping list program– Implement findTotal( ) and toString( )
• Pass array to function – yes
• Some notes on style
• Some common mistakes
Shopping list
• 2 classes: Item and ShoppingList
ShoppingList:• findTotal()
– We already know how to add up elements of an array, but this time it’s a little different.
sum = sum + list[index].getPrice( );
• toString() needs to show a whole list– String.format ( )helps align the columns
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)
Homework design
• For the climate homework problem, one design issue is: where should we read the input file & initialize our arrays? Two possibilities:– In City constructor
this constructor will be default, do I/O, allocate space for array, and initialize
– In main( ) before we call the City constructor.
We create arrays in main( ), and pass them to an initial-value constructor.
Good style
• Comments at top of source file, and before each function.
• “Line” comments, if the function does several things• Readability: blank lines and spaces• Indentation
– Body of function, if-statement, or loop• Vertically align curly braces• Meaningful variable names• Solution should be reasonably concise
– Don’t copy/paste code.
What’s wrong…?
System.out.printf(“Enter number of people: “);
int numPeople = in.nextInt();
if (numPeople = 0)
System.out.printf(“Can’t be zero!”);
---------------------------------------------
String correctPassword = “Furman#1”;
String password = in.next();
if (password == correctPassword)
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.
System.out.printf(“Ready to quit? (y/n): “);
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.
String answerString = “answer” + a + b;
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” checkerif (credits >= 88 && clp >= 24) return “senior”;else if (credits >= 58 && credits < 88 &&
clp >= 16 && clp < 24) return “junior”;else if (credits >= 28 && credits < 58 &&
clp >= 8 && clp < 16) return “sophomore”;
else return “freshman”;
CS 11 – Oct. 15
• 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
CS 11 – Oct. 17
• To write fun programs like games, we should invest some time looking at better ways to do things in Java.
– More operations (e.g. +=) – Better ways to loop– Other ways to make choices– Better arrays
If a problem can be solved, there’s an infinite number of ways to do it.
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 = 2;
b = 3;
c = 5;
c *= 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” associative8 – 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 = b = c = 3;
d = 2 * ++a; // a = 4. Then, d = 2*4 = 8.
e = 2 * b++; // e = 2*3 = 6. Then, b = 4.
f = 2 * (c+1); // f = 2*4 = 8. c is unchanged.
• To minimize confusion, I always use prefix form (++a) unless I really need suffix form (a++).
Examples
48 / 6 / 3
a = 1;
b = 2;
c = 3;
a = b = c;
a = 4;
b = 3;
c = 2;
b += c;
a -= b;
c *= 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 (in.hasNext())
{
wordArray[count++] = in.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
“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);
Example
• For-loop:
for (i = 0; i < s.length(); ++i)
{
if (s.charAt(i) == ‘t’)
++count;
}
• Equivalent while-loop
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) // if i already init.
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!
CS 11 – Oct. 20
Loops
• 3 kinds √• Taking control inside a loop
– Breaking out of a loop– Continuing to the next iteration
• Using nested loops
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 – do iterations 1-10, but skip #3for (i = 1; i <= 10; ++i)
{
if (i == 3)
continue;
// rest of loop
Nested loop
• “Loop within a loop”– Allows computer to do a lot of work!
– Useful for multi-dimensional information• Tic-tac-toe, connect 4, chess, …• Airline and room reservations
– Useful for I/O for rows & columns of data• Including images: rows/columns of pixels
Nested loop
• We’re already used to the idea:– For each week…
• for each day
– For each line… • for each word on the
line
– For each building• For each room
• Don’t confuse nested loop with consecutive loop
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;
Practice
• An easy way to start practicing with nested loops is to experiment printing out some rectangular patterns.
• How would you print out:
*********************
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.
Mystery
for(i = 1; i <= 5; ++i)
{
for (j = 1; j <= 5; ++j)
System.out.printf("*");
System.out.printf("\n");
}
• What is the output?
• What happens if we change the j <= 5 to j <= i ?
Can we do this?
• How can we get a nested loop to print out these numbers:1 2 3 4 51 2 3 41 2 31 21
• 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.
2-d patterns
• How can we create these floor tile designs?
X X X X X X X XXXX XXXX XXXX XXXX
X X X X X X XXX XXXX XXXX XXXX
X X X X X X X XX XXXX XXXX XXXX X
X X X X X X X XXXX XXXX XXXX XX
X X X X X X X XXXX XXXX XXXX XXX
X X X X X X XXXX XXXX XXXX XXXX
X X X X X X X XXX XXXX XXXX XXXX
XX XXXX XXXX XXXX X
CS 11 – Oct. 22
• Nested loops √– Ex. Creating a checkerboard pattern
• 2-D arrays– Useful for board games, creating images– Declare, allocate, initialize, use– Accessing elements
– There’s actually no limit on how many dimensions you may have.
Arrays
• Nested loops are very practical for multidimensional arrays.
• Declare & allocateint [][] a = new int [8][10];
• Initializefor (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;
}
}
}
• Can adapt solution 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.
Due to spacelimitations, declarations of
i and j are not shown.
Traversal
• With a nested loop, we can visit all the cells in a 2-D array.
• What can one loop do?– Suppose array a is 10x10. Try these examples:
for (i = 0; i < 10; ++i)
a[i][3] = in.nextInt();
for (i = 0; i < 10; ++i)
a[7][i] = 42;
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
Error checking
needInput = true
while (needInput)
{
int length = ...
int width = ...
// check to see if both are valid...
}
Box b = new Box(length, width);
See anything wrong?
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 on the comparison:– Test only one variable or expression– Only “integral” types (int, char)– Only compare == – Only compare to constants
• 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:
case 11: days = 30;
break;
default: days = 31;
break;
}
Can combine several cases
“default” means “for all other cases”
Example (2)
// Let’s convert suit letter to string.
switch (suitChar)
{
case ‘h’: suitName = “heart”;
break;
case ‘d’: suitName = “diamond”;
break;
case ‘s’: suitName = “spade”;
break;
case ‘c’: suitName = “club”;
break;
}
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
• Driver class– Create 5 cards, make a hand and evaluate it.
• Hand class– Attributes: 5 card 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” !
Enhancements?
• Card class– new constructor that takes integer (1-52) and figures
out corresponding denomination & suit.
• Deck class (new)– we can “shuffle” all the cards– Return a random card
• Driver– Sort cards in our hand– allow user to replace card
CS 11 – Oct. 27
Poker, continued• New Card constructor
– integer (1-52) denomination & suit.
• New Deck class– Shuffle, and deal random card
• Driver– Sort cards in our hand– 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
Spades are 40-52.
Card numbers
denom Clubs Diamonds Hearts Spades
A 1 14 27 40
2 2 15 28 41
3 3 16 29 42
… … … … …
J 11 24 37 50
Q 12 25 38 51
K 13 26 39 52
Given a number 1-52, how do we determine:• Denomination• Suit
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!
CS 11 – Oct. 29
• Sorting an array– One method is “swap sort”– How do you swap?– Need to compare cards
• Static function– Helpful to avoid repetitious code in Driver
• Javadoc– Automatic HTML documentation– Can run at command line or within Eclipse.
“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;
}
Static function
• Purpose– 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)
• How to call function: is it located in same file?– YES: just give function name + parameters. For
example: sort(hand)– NO: prepend classname. For example: Math.sqrt(3).
Function calls
• Let’s review what a function call looks like– Disregarding the parameters.
• functionName( )– Must be located in the same source file as the call. May
be instance function or static function. You have to look at declaration to be sure.
• object.functionName( )– Find out which class object belongs to. That source file
contains the function.
• ClassName.functionName( )– Static function located in that Class.
Javadoc comment
• Enclosed by /** and */• Can provide extra information by using “@ tags”
@param param_name description
@return describe what’s being returned
@deprecated
@author
• Once you see your comments in HTML, you can more easily see what documentation is missing or is hard to understand.
CS 11 – Oct. 30
• 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
CS 11 – Oct. 31
• 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”– Must know size in advance– 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( )• add( )• 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>();
// adding elements
Card c1 = new Card(27);
hand.add(c1);
hand.add(new Card('2','d'));
…
// 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>();
a.add(16);
a.add(25);
a.add(36);
a.add(49);
// 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
– 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)
– Read more about ArrayList and Integer online.
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
• User login accounting– 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.
• Organizing stock trades– Arrange each (buy/sell) transaction by company.– We don’t know how many distinct companies there
are in the input.
CS 11 – Nov. 3
• Blackjack hint: how can we compute the value of a hand?
• Practice with ArrayList: user-login example– ArrayList functions add( ), get( ), set( ), size( ).
Value of hand
• Goal is to get closest to 21 w/o going over.– (The house must hit until value >= 17.)
• Ace can be worth 1 or 11, whichever helps.
• Does this work?
for each card in my hand:
accumulate cardValue to my handValue
if (card is ace && handValue < 21)
let the ace count 11 instead of 1
Case study
• User-login accounting:
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
Goals
• Print a list of all users, displaying how many times each person logged in.– Can also keep track of total login time, but we need
more practice with reading input.
• Make output format more attractive.– toString() or in main()
• Find total number of logins.• Sort the list so most active users appear first.• Allow us to search the list for a user’s name.
Design issues
• Where is input coming from?– Should we ask user for file name?
• User class:– What attributes, operations do we need?– It’s okay not to know everything up front. We can add
more later.
• Driver– Should we read file here?– When do we create the ArrayList of Users?– What is the format of the input?– How do we ensure we don’t repeat names in list?
CS 11 – Nov. 5
• User-login example– Finish design– Run program… see what improvements should be
made– Practice with ArrayList functions
Goals
• Print a list of all users, displaying how many times each person logged in.– Can also keep track of total login time, but we need
more practice with reading input.
• Make output format more attractive.– toString() or in main()
• Find total number of logins.• Sort the list so most active users appear first.• Allow us to search the list for a user’s name.
Final version
User class• Attributes
– Name– numLogins
• Operations– i-v constructor– getName– getNumLogins– toString – addLogin
Driver• Open file• Create new list• Read each line
– If blank, done with input.
– Read user’s name
– Have we seen it before?• Create new User object• Or, just add 1 to existing
• Print total # users• Sort & print out list• Search for 1 name in list.
CS 11 – Nov. 7
• 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)
{
ask user for input
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 – Nov. 10
• Conditional operator– Short cut to doing an “if” statement
• Character processing– Applying arithmetic on characters– Examples: cryptography, Hangman game.
Conditional operator
• How can we fix this?
System.out.printf(“I found %d logins\n”, count);
• 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,
count == 1 ? “login” : “logins”);
• Absolute value of the difference: | x – y |
abs = x-y >= 0 ? x-y : y-x;
// Feel free to add parentheses for readability.
• 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• Each character value has a numerical representation.• We can use + and – on characters.
• How would you print out alphabet?
• char operations – Important for cryptography– Example: add 3 to every letter in a word:
“hungry dog” could be encoded as “kxqjub grj”
(Adding a constant to each letter is called a Caesar cipher.)
Caesar cipher
String plain = “hungry dog”;
String cipher = “”;
for (int i = 0; i < plain.length(); ++i)
{
char c = plain.charAt(i);
if (c >= ‘a’ && c <= ‘z’)
{
c += 3;
if (c > ‘z’)
c -= 26;
}
cipher += c;
}
Case study
• Hangman game – Play game to inspire our solution.– Design: we need a “game” class.
– Driver: simple loop where user makes guesses until game is over.
– Game has several attributes such as:• Correct answer• Display: show what part of the word is known to player• Number of bad guesses• Remember previous guesses
CS 11 – Nov. 12
• Hangman game– Example of using char type
– Let’s design this program. We’ve seen how it should work.
– Implementation (handout)
Design issues
• hangman game…– Start with a design: we need a “game” class.
– Driver: simple loop where user makes guesses until game is over.
– Several attributes such as:• Correct answer• Display: show what part of the word is known to player• Number of bad guesses• Remember previous guesses
continued
Other issues– 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.
CS 11 – Nov. 17
• 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 – Nov. 21
• Tokenizing strings– Scanner √– StringTokenizer– String’s split ( )
• Examples– Add all the numbers in “16 7 4 1 9 12 3”– Win/loss record– Return to login program (times)
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(); // “entrée”
String token2 = scan.next(); // “8.95”
// ETC.
• 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.
Using split
• 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+”);
Examples
• Most of the time, StringTokenizer is most straightforward approach. Use whatever you think is most productive.
• Reading win-loss records. “47-27-8”– 2 points for each win, 1 point for OTL
• Reading time “(1+19:32)”– countTokens( ) can tell us if days are included.
Having 2 tokens means it’s just hours and minutes.
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
• Hint: The first number is:
Integer.parseInt(args[0])
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 timedo somethingt2 = check the timeelapsed time = t2 – t1
Examples
long t1 = System.
currentTimeMillis();
for (i=0; i<1000; ++i)
a[i] = gen.nextInt();
long t2 = System.
currentTimeMillis();
long t3 = System.
currentTimeMillis();
for (i=0; i<1000; ++i)
a[i] = 0;
long t4 = System.
currentTimeMillis();
As a result, we can find how long it takes Java to generate a random number, which is probably < 1ms.
((t2 – t1) – (t4 – t3)) / 1000
Web Robot
• 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!
CS 11 – Dec. 1
• Software design– Managing a larger program– Class relationships
• Interface – helpful tool for design
• Two kinds of relationships classes can have:– Aggregation: “has a” – Inheritance: “is a”
Interfaces
• Idea is simple: it’s a “to-do” list of all the functions we want to implement for our class.
• 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.
Examples
• Interfaces are 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– Maintaining a list: use array or ArrayList?
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!
Encryption
• Specific example of using an interface: there are various ways to encrypt.– Caesar cipher– Xor function– Many other ways to encrypt!
• Encryption.java = interface• Caesar.java and Xor.java “implement the interface”• Driver.java Chooses one implementation
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!
Multiple classes
• When a program consists of several classes, very often there is some relationship among them.– Aggregation (“has a”)
One class contains attributes that are objects of another class.
– Inheritance (“is a”)
One class is a specialized version of another class.
CS 11 – Dec. 3
Aids to large programming• Work on a team!• Look for class relationships
– Interface: classes sharing common functionality √
– Aggregation: one class contained in another (“has a”)
– Inheritance: one class is a more specialized version of an existing one (“is a”)
Aggregation
• “X has a Y” relationship between classes. Very common.
• Happens when 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
Inheritance
• 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
• Where is the inheritance?
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.
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.
Design
Vehicle class
weight
fuelType
capacity
(constructor)
cruisingRange()
fillErUp()
drive()
changeOil()
Car class
air bag
radio
(constructor)
wash()
Tank class
weapons
radar
(constructor)
fire()
Inheritancesimplifies design of
subclasses.
CS 11 – Dec. 5
• Inheritance– implementation– Zoo example– polymorphism– instanceof (keyword in Java)
• GUIs – JOptionPane built-in class– applets
Lab review
• 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.– (To make chocolate chip cookies, you need to know how to
make a basic cookie.)– For default constructors, this happens automatically .
Otherwise, we have to call “super(…)” ourselves.
• Subclasses may override function from ancestor– We may want to re-define drive() or toString(), etc.
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.• I decided to implement exercise() inside Animal. We need to
know what kind of animal, to do appropriate workout.
CS 11 – Dec. 8
• Class relationships √– Interface, inheritance, aggregation– Polymorphism
• Application: GUIs – JOptionPane class– Applets– Full stand-alone applications!
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(); // general
creature = new Dwarf(); // specific
...
creature = new Toad(); // 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>
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.
Applet structureMy Applet class: attributes
init(): Create objects to draw Start the listener
Listener class:
call repaint()
paint():
Executed once, at beginning
Executed when there is a mouse event.
Executed when window refreshed.
Attributes help usdetermine what to
to draw.
Listener class: Grab x,y values call repaint()
Example
• 8x8 array “box” of Rectangles to draw• 8x8 array of int storing who is occupying “board”
0 = position is empty1 = occupied by Blue player2 = 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[ ] [ ].
top related