261
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.

CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

Embed Size (px)

Citation preview

Page 1: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

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.

Page 2: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

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

Page 3: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

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

Page 4: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

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.

Page 5: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

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!

Page 6: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

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.

Page 7: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

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.

Page 8: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

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.

Page 9: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

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.

Page 10: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

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?

Page 11: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

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.

Page 12: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

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.

Page 13: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

CS 11 – March 4

Overview, continued

• Languages for the computer• What does software look like?• Problem-solving procedure

Page 14: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

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.

Page 15: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

Compiling

Javaprogram

Javacompiler

Bytecode

Can execute in CPU.

Compiler reads your program.

It checks for simple mistakes, and then translates your code into binary.

Page 16: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

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.

Page 17: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

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

Page 18: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

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.

Page 19: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

CS 11 – March 5

• You can find class notes oncs.furman.edu/~chealy/cs11

• 2 adder programs

• Problem-solving procedure.

• Let’s hold off on the “nuts and bolts” until tomorrow.

Page 20: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

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.

Page 21: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

Need a plan

• Often a bad idea to rush to keyboard and start typing code.

• Problem solving procedure:

(See handout)– design– implementation

Page 22: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

Advice

• 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.

Page 23: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

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.

Page 24: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

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.

Page 25: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

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.

Page 26: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

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)

Page 27: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

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.

Page 28: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

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.

Page 29: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

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

Page 30: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

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.

Page 31: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

Recap

• 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 = 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();

Page 32: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

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.

Page 33: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

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

Page 34: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

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.)

Page 35: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

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

Page 36: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

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 %)

Page 37: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

CS 11 – March 10

• Finish: integer vs. real-number division– Can change type of expression– Look at remainder

• More on the if-statement.

• Get ready for lab– We’ll use Eclipse: a program that can help us edit,

compile, run and debug software we create.

Page 38: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

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) !

Page 39: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

/ 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

Page 40: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

If-statement

• As we saw before, used 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!

Page 41: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

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);

Page 42: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

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”);

Page 43: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

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

Page 44: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

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)

• 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.

Page 45: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

CS 11 – March 11

• Recap of yesterday

• Types of errors

• Other print functions

• Strings

Page 46: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

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……….. ||

Page 47: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

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.

Page 48: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

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.

Page 49: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

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);

Page 50: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

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

Page 51: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

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”

Page 52: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

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”

Page 53: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

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"

Page 54: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

CS 11 – March 12

• Strings– Comparing– Review StringFun handout

• Being able to repeat steps– Lots of data / input– Avoid tedium using a loop

Page 55: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

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.

Page 56: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

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

Page 57: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

String handout

• StringFun.java features these String functions:– charAt– equals and equalsIgnoreCase– compareTo– startsWith and endsWith– length– indexOf and lastIndexOf– substring– replace

Page 58: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

Next problem

• How would you add 5 numbers?int first = sc.nextInt();

int second = sc.nextInt();

int third = sc.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.

Page 59: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

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.

Page 60: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

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.

Page 61: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

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 = sc.nextInt();

sum = sum + newNumber;

count = count + 1;

}

System.out.printf("The sum is %d\n");

This solutionscales well forlarger input.

Page 62: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

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.

Page 63: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

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);

}

Page 64: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

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.

Page 65: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

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

Page 66: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

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

Page 67: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

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”));

Page 68: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

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

Page 69: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

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.)

Page 70: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

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?

Page 71: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

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?

Page 72: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

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();

Page 73: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

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.

Page 74: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

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.

Page 75: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

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)

Page 76: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

CS 11 – March 18

• Error checking: use 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.}

Page 77: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

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”);

}

Page 78: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

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 shouldstrive to have solutions

that are easy to understand

If you have a “clever”solution, please writea careful comment

explaining it.

Page 79: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

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().

Page 80: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

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

Page 81: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

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.)

Page 82: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

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?

Page 83: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

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.

Page 84: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

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.

Page 85: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

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.

Page 86: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

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

}

Page 87: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

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

Page 88: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

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

Page 89: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

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

Page 90: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

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”

Page 91: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

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

Page 92: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

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; …

Page 93: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

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;

}

Page 94: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

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?

Page 95: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

CS 11 – March 27

• Program design– Defining a class with: attributes and operations– Continue with Account example

• Problem solving with OO approach

• Constructors• Constants

Page 96: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

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

Page 97: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

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());

Page 98: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

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

Page 99: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

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...

Page 100: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

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);

Page 101: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

// 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;

}

Page 102: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

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;

Page 103: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

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 .

Page 104: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

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.)

Page 105: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

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.

Page 106: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

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);

}

Page 107: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

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.

Page 108: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

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

Page 109: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

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

Page 110: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

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

Page 111: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

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.

Page 112: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

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.

Page 113: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

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 – Read string and 3 integers– 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

Page 114: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

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

Page 115: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

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.

Page 116: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

CS 11 – April 3

• Pass array to function – yes

• Some common mistakes

Page 117: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

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)

Page 118: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

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;

Page 119: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

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”);

Page 120: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

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;

Page 121: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

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);

Page 122: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

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);

Page 123: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

What’s wrong?

// A “CLP” checkerif (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”;

Page 124: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

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

Page 125: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

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.

Page 126: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

afterward

• Which then leaves fun stuff. For example,– Applets– Creating images– Inheritance– Interfaces– Exceptions– Web robot

Page 127: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

CS 11 – April 8

• Recap lab

• Helpful Java features– Important aids to productivity– Review operators– Loops

• Different kinds of loops• Using multiple loops

– Making choices– Javadoc (comments formatted as Web page)

Page 128: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

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]

Page 129: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

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++ )

Page 130: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

Order of ops

• Do operations in this order:

* / %

+ -

< > <= >= == !=

&&

||

= += -= *= /= %=

• Examples:

a = 2;

b = 3;

c = 5;

c *= a + b;

g = a > b || b > c;

Page 131: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

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)

Page 132: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

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 use prefix form (++a) all the time unless I really need suffix form (a++).

Page 133: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

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++);

Page 134: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

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();

}

Page 135: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

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

Page 136: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

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

Page 137: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

“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);

Page 138: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

How it works

• A for-loop has 4 parts.

for ( 1 ; 2 ; 3 )

4

(exit loop when false)

Page 139: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

For = while

• For-loop:

for ( 1 ; 2 ; 3 )

{

4

}

• Equivalent while-loop

1

while ( 2 )

{

4

3

}

Page 140: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

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!

Page 141: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

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.

Page 142: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

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);

Page 143: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

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);

Page 144: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

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!

Page 145: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

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!

}

Page 146: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

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!

Page 147: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

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.

Page 148: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

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

Page 149: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

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;

Page 150: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

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.

Page 151: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

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).

Page 152: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

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.

Page 153: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

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

Page 154: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

2-d patterns

• How can we create these:

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

Page 155: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

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.

Page 156: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

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.

Page 157: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

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

Page 158: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

CS 11 – April 15

• What is bug in ttt program?

• Recap error checking– Scope of variables– Definite assignment

• Switch statement

Page 159: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

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).

Page 160: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

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.

Page 161: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

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”

Page 162: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

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;

}

Page 163: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

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 …

Page 164: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

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” !

Page 165: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

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?

Page 166: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

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.

Page 167: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

CS 11 – April 17

• Sorting an array

• Modify poker program so it allows user to replace cards.

Page 168: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

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

Page 169: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

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!

Page 170: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

“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;

}

Page 171: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

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.

Page 172: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

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;

}

Page 173: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

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)

Page 174: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

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

• Javadoc– Automatic HTML documentation– Can run at command line or within Eclipse.

Page 175: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

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.

Page 176: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

CS 11 – April 22

• ArrayList built-in class– Contrast with arrays– Operations– Special handling for primitive types– Practical examples

See handout also.

Page 177: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

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];

Page 178: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

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.

Page 179: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

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

Page 180: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

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.

Page 181: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

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();

Page 182: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

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)

Page 183: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

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!

Page 184: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

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.

Page 185: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

CS 11 – April 23

• 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

Page 186: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

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.

Page 187: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

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

Page 188: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

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

Page 189: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

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!

Page 190: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

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?

Page 191: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

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.

Page 192: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

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

Page 193: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

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”);

}

Page 194: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

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.

Page 195: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

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.

}

Page 196: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

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.

Page 197: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

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.

Page 198: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

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>

Page 199: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

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...

Page 200: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

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.

Page 201: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

CS 11 – April 30

• Case study: 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

Page 202: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

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.

Page 203: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

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 Javadoc

• ArrayList• Exceptions• Conditional operator• Character processing• Case studies

– Poker– User-login– Hangman

Page 204: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

CS 11 – May 5

• What’s left?– Tokenizing– Creating images– Useful tricks (java-archive, persistent objects)– Designing larger programs– Applets and GUIs

Page 205: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

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( )

Page 206: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

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.

Page 207: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

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();

Page 208: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

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

}

Page 209: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

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).

Page 210: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

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.

Page 211: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

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+”);

Page 212: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

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!

Page 213: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

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

Page 214: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

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

Page 215: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

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.

Page 216: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

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.

Page 217: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

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 !)

Page 218: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

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.

Page 219: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

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

Page 220: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

How they work

101011 101011 101011& 011001 | 011001 ^ 011001--------------- --------------- --------------- 001001 111011 110010

The ~ operator is easy. It just inverts all the bits:~(101001) equals:

010110

Page 221: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

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”.

Page 222: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

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

Page 223: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

Print binary

Here’s how to do it:

value = 278; // or anything we want

for (n = 31; n >= 0; --n)

{

mask = 1 << n;

if ((value & mask) != 0)

System.out.printf(“1”);

else

System.out.printf(“0”);

}

System.out.printf(“\n”);

Page 224: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

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”

Page 225: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

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!

Page 226: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

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

Page 227: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

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

Page 228: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

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.

Page 229: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

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

Page 230: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

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

Page 231: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

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!

Page 232: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

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

Page 233: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

“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?

Page 234: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

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

Page 235: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

Examples

Animal

Fish Reptile Bird

Snake Penguin

Room

Bedroom Kitchen

Vehicle

Car Tank

Page 236: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

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.

Page 237: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

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.

Page 238: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

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.

Page 239: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

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().

Page 240: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

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.”

Page 241: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

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!

Page 242: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

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.

Page 243: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

CS 11 – May 15

• Inheritance– Zoo example– polymorphism– instanceof (keyword in Java)

• GUIs – JOptionPane built-in class– applets

Page 244: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

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.

Page 245: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

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

...

Page 246: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

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.

Page 247: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

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!

Page 248: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

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>

Page 249: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

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”

Page 250: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

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

Page 251: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

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.

Page 252: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

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

Page 253: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

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()

Page 254: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

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.

Page 255: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

Mouse Applet 4

• Same 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[ ] [ ].

Page 256: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

CS 16 – May 20

Some useful tools

• Command line arguments• Timing your code• Web robot

Page 257: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

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.

Page 258: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

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.

Page 259: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

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

Page 260: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

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.– Don’t count the overhead! – “Dual loop” method.

Page 261: CS 11 – March 3 Course overview –Computers & computer science –Nature of problem solving Tomorrow, we’ll continue with –What software looks like –Problem-solving

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!