780 likes | 985 Views
CSC 176: Introduction to Programming. Fall 2005 Dr. Chuck Lillie. Course Outline. Goals: Learn to access Java environment Learn to design and implement Java programs Learn to evaluate and correct Java programs Objectives: By the end of this course the student should be able to:
E N D
CSC 176: Introduction to Programming Fall 2005 Dr. Chuck Lillie
Course Outline • Goals: • Learn to access Java environment • Learn to design and implement Java programs • Learn to evaluate and correct Java programs • Objectives: • By the end of this course the student should be able to: • Access Java environment • Design Java programs • Implement Java programs • Evaluate Java programs • Correct errors in Java programs • Evaluation • Homework/Programming 35% • Two Exams 30% (15% each) • Final Exam 35%
Course Outline • Lab 1 • How to access the Java environment & standard output stream • Lab 2 • Operator order of precedence • Declarations • Standard input stream • Expressing mathematical equations • Class methods • Lab 3 • String class • Object variable references • Null references and unassigned variables • Using member methods
Course Outline • Lab 4 • Class design • Data abstraction • Information hiding • Instance variables • Accessor methods • Mutator methods • Constructors • Facilitator methods • Graphics.drawArc() and Graphics.fillArc() methods • Lab 5 • The if statement • Boolean logic • Truth tables • The switch statement • Comparing objects using equal()
Course Outline • Lab 6 • Looping • while statement • do while statement • for statement • File stream extraction • Lab 7 • Parameter passing • Methods inherited from Object • Overriding methods • static methods • java.util.Random class • Scope and name reuse
Course Outline • Lab 8 • One-dimensional arrays • Subscripting • Array manipulation • Searching techniques • Java collection framework • Iterators • ArrayList • Lab 9 • Inheritance • Inheritance hierarchies • Polymorphism • abstract classes • protected access • Overriding inherited methods • Extending swing class • Overriding paintComponent() • Proper use of repaint()
Course Outline • Lab 10 • Throwable class hierarchy • Throwing exceptions • Exception propagation • try-catch blocks • Subclass exceptions • Finally • Lab 11 • Using activation records to trace recursion • Mutual recursion • Recursive binary search • Lab 12 • Timer class • TimerTask class • Fixed-rate vs. fixed-delay scheduling • Swing-based animation • Creating tasks at runtime • Final project
Problem Solving Determine Analysis problem features Rethink as appropriate Describe objects Design and methods Produce the Implementation classes and code Examine for Testing correctness
Problem Solving -- Problem Definition • A clear statement of the problem • Defines problem without any reference to solution • Should be in user’s language • Not in technical terms Failure to define problem may cause you to solve the wrong problem
Problem Solving -- Analysis • Do I really understand the problem? • What exactly does the input consist of? • What exactly are the desired results or output? • Can I construct an example input small enough to solve by hand? • What happens when I try to solve it? • How important is it to my application that I always find an exact, optimal answer? Can I settle for something that is usually pretty good? • How large will a typical instance of my problem be? Will I be working on 10 items? 1,000 items? 1,000,000 items? • How important is speed in my application? Must the problem be solved within one second? One minute? One hour? One day? • How much time and effort can I invest in implementing my algorithm? Will I be limited to simple algorithms that can be coded up in a day, or do I have the freedom to experiment with a couple of approaches and see which is best? • Am I trying to solve a numerical problem? A graph algorithm problem? A geometric problem? A string problem? A set problem? Might my problem be formulated in more than one way? Which formulation seems easiest?
Problem Solving -- Reuse • Is my problem in a catalog of algorithmic problems? • If it is, what is known about the problem? Is there an implementation available that I can use? • If I don't see my problem, did I look in the right place? Did I browse through all the pictures? Did I look in the index under all possible keywords? • Are there relevant resources available on the World-Wide Web? Did I do a Google, Lycos, Alta Vista, or Yahoo search?
Problem Solving -- Design • Can I find a simple algorithm or heuristic for the problem? • Can I find an algorithm to solve my problem correctly by searching through all subsets or arrangements and picking the best one? • If so, why am I sure that this algorithm always gives the correct answer? • How do I measure the quality of a solution once I construct it? • Does this simple, slow solution run in polynomial or exponential time? Is my problem small enough that this brute-force solution will suffice? • If I can't find a slow, guaranteed correct algorithm, why am I certain that my problem is sufficiently well-defined to have a correct solution? • Can I solve my problem by repeatedly trying some simple rule, like picking the biggest item first? The smallest item first? A random item first? • If so, on what types of inputs does this heuristic work well? Do these correspond to the data that might arise in my application? • On what types of inputs does this heuristic work badly? If no such examples can be found, can I show that it always works well? • How fast does my heuristic come up with an answer? Does it have a simple implementation?
Problem Solving -- Design • Are there special cases of the problem that I know how to solve exactly? • Can I solve the problem efficiently when I ignore some of the input parameters? • What happens when I set some of the input parameters to trivial values, such as 0 or 1? Does the problem become easier to solve? • Can I simplify the problem to the point where I can solve it efficiently? Is the problem now trivial or still interesting? • Once I know how to solve a certain special case, why can't this be generalized to a wider class of inputs? • Is my problem a special case of a more general problem in the catalog?
Problem Solving -- Design • Which of the standard algorithm design paradigms are most relevant to my problem? • Is there a set of items that can be sorted by size or some key? Does this sorted order make it easier to find the answer? • Is there a way to split the problem in two smaller problems, perhaps by doing a binary search? How about partitioning the elements into big and small, or left and right? Does this suggest a divide-and-conquer algorithm? • Do the input objects or desired solution have a natural left-to-right order, such as characters in a string, elements of a permutation, or the leaves of a tree? If so, can I use dynamic programming to exploit this order? • Are there certain operations being repeatedly done on the same data, such as searching it for some element, or finding the largest/smallest remaining element? If so, can I use a data structure to speed up these queries? What about a dictionary/hash table or a heap/priority queue? • Can I use random sampling to select which object to pick next? What about constructing many random configurations and picking the best one? Can I use some kind of directed randomness like simulated annealing in order to zoom in on the best solution? • Can I formulate my problem as a linear program? How about an integer program? • Does my problem seem something like satisfiability, the traveling salesman problem, or some other NP-complete problem? If so, might the problem be NP-complete and thus not have an efficient algorithm?
Problem Solving -- Design • Am I still stumped? • Am I willing to spend money to hire an expert to tell me what to do? If so, check out the professional consulting services mentioned in Section . • Why don't I go back to the beginning and work through these questions again? Did any of my answers change during my latest trip through the list?
Problem Solving – General Rules • Identify the inputs • Identify the outputs • Break problem into smaller sub-problems • Identify the functions required • Outline the solution or draw a diagram • Identify how individual pieces will interact (identify interfaces between components) • Start with implementation for specific input • Refine to more general solution • Don’t be afraid to rebuild • Don’t be afraid to try something new
Lab 1 • How to access the Java environment & standard output stream • Compile .java program • Double click on .java program • JCreator program will open with .java program in main window • Select Build from menu bar • Select Compile from drop-down menu • Execute compiled program • Select Build from menu bar • Select Execute File from drop-down menu • Click on … to select the path and file to execute • Click on down arrow on Files of type • Select All Files (*.*) • Change Look in to the directory where your .java program is stored • Select the .class file that you want to execute • Select Open • Select OK
Lab 2 • Operator order of precedence • Declarations • Standard input stream • Expressing mathematical equations • Class methods
Operator Precedence • The precedence for the arithmetic, relational, Boolean operators, and assignment from highest to lowest is: Operation Symbol Precedence Association ---------------------------------------------------------------------------------------------------------------------------- (from highest, 1, to lowest, 11) grouping ( ) 1 left to right unary + - 2 right to left multiplication * 3 left to right division / 3 left to right remainder % 3 left to right addition + 4 eft to right subtraction - 4 left to right less than < 5 left to right less than or equal <= 5 left to right greater than > 5 left to right greater than or equal >= 5 left to right equal == 6 left to right not equal != 6 left to right bit and & 7 left to right xor ^ 8 left to right bit or | 9 left to right conditional and && 10 left to right conditional or || 11 left to right assignment =, +=, *= ... 12 N.A.
Object • An object is a structure that represents a state and knows methods to manipulate it. The structure components are called instance variables.
Class • A class consists of all objects with like state which know exactly the same methods, i.e., a class knows the structure of its objects and contains the methods to manipulate the structure. An object is called an instance of a class. • Given a class, one normally creates objects. Objects are created dynamically with the prefix operator new which in turn calls a constructor method to initialize the instance variables. Uninitialized instance variables are zeroed. • Methods mostly access the instance variables of the receiver. If methods return their receiving objects, method calls (messages) can be cascaded.
Object Declarations • Each object must be declared. • Example of a declaration: • MainWindow mainWindow; • mainWindow is an identifier. The value of the identifier can be a reference to a MainWindow object. • At this point of the program, the value of the identifier is null. This means, you can't send a message to the object. • Example of creating an object and assign it to a identifier: • mainWindow = new MainWindow();
Identifier • An identifier is an unlimited-length sequence of Java letters and Java digits, the first of which must be a Java letter. An identifier cannot have the same spelling as a keyword, Boolean literal, or the null literal. • Can be any length • First character must be a letter \ { 0, .. 9 } • Following characters can be letters or digits • Are case sensitive: TOM is NOT the same as Tom • A Java reserved word CANNOT be used as an identifier, ex. true • Must be declared to be of some type.
Identifier (cont.) • Identifier should/must be self explained. • The words i, k, lth, ... have no real meaning for a human being. • lessThanTen versus ltt • thisIsSorted versus t • mph versus speed • maximum versus m • The basic syntax for declaring variables is: • typename identifier; • typename identifier = expression; • A variable has the following properies: • memory location to store the value. • type of data stored in the memory location. • name used to refer to the memory location.
Character • Java uses the unicode standard. The type char has 16 bits and is not considered to be an integer type. • The use of 16bits allows us to use most written languages. • Arabic • Gurmukhi • Miscellaneous Symbols • However, char values can be converted into arithmetic values and vice versa. Other than that, char values can only be compared and assigned. • The class Character provides, among others, class methods to classify characters that are used in char/Wc . • Character constants consist of a character in single quotes. There are (only!) the following escape conventions as in C: • -- \b \f \n \r \t • -- \\ \' \" • -- \o \oo \ooo • with 1 to 3 octal digits for an 8 bit value. • Every character in the program source can be represented with hexadecimal digits in unicode as \uxxxx; however, replacement happens very early and is no alternative to \n etc.
Character Example • Output: a a Character.isDigit('a') false Character.isDigit('0') true Character.isDigit('0') true c_1 != c_2 c_1.equal(c_2) /* * * This program is using the Character class * @version $Id$ * @author Hpb * Revisions: * $Log$ */ import javabook.*; class Char_1 { public static void main( String args[] ) { Character c_1 = new Character('a'); Character c_2 = new Character('a'); System.out.println(c_1 + " " + c_2); System.out.println("Character.isDigit('a') " + Character.isDigit('a')); System.out.println("Character.isDigit('0') " + Character.isDigit('0')); System.out.println("Character.isDigit('0') " + Character.isDigit('0')); if ( c_1 == c_2 ) System.out.println("c_1 == c_2"); else System.out.println("c_1 != c_2"); if ( c_1.equals(c_2) ) System.out.println("c_1.equal(c_2) "); else System.out.println("!c_1.equal(c_2) "); } }
Java Primitive Types • A primitive type is predefined by the Java language and named by its reserved keyword. • A variable has the following properies: • memory location to store the value. • type of data stored in the memory location. • name used to refer to the memory location. • Java knows the following types: type #bits def. v. minimum value maximum value ------------------------------------------------------------------------------------------------ byte 8 bits 0 -128 127 char 16 bits 0 0 65,535 short 16 bits 0 -32,768 32,767 int 32 bits 0 -2,147,483,648 2,147,483,647 long 64 bits 0 -9,223,372,036,854,775,808 9,223,372,036,854,775,807 float 32 bits 0.0 -3.40282347E38 3.40282347E38 double 64 bits 0.0 -1.79E+308 1.79E308
Types – Example int index; int milesPerHour, maximumSpeed; float pressure, sizeOfme; double starTrekSpeed; int picturesTakenSofar = 20; double probability = 0.789; • Conditions can only be expressed with Boolean values. • Boolean has the predefined constants • true and • false. • The names are not reserved; however, they are only recognized as Boolean constants.
Arithmetic Operators • The table below shows some of the arithmetic operators that Java provides in the order of their precedence. • Parentheses can be used to change the order of evaluation • An arithmetic expression returns (calculates) a value when executed. binary Operator Description ------------------------------------------------------------------- + addition - subtraction * multiplication / integer division, if both operands are integer; real division otherwise % remainder unary Operator Description ------------------------------------------------------------------------ ++ increment by 1 -- decrement by 1 ! not
Arithmetic Operators -- Examples int left; int right; int result; left = 4; right = 3; result = 4 * 3; result = 4 + 3; result = 4 / 3; result = 4 % 3; left ++; result = left++; result = ++left; right ++; result = right++; result = ++right;
Mixed Mode Arithmetic and Casting • When an expression contains more than one arithmetic type all are converted to the heaviest. byte short int long float double • For example, 2 + 3.3 is interpreted as 2.0 + 3.3. • Java is strongly typed. However, the type of the results of evaluating an expression may be changed using casting. To cast, place the target type in parentheses before the operand or expression to be converted. • For example, if we really wanted the results of 2 + 3.3 to be integer, we could use int index; index = 2 + (int) 3.3; index = (int) (2 + 3.3);
Casting Example • Results % javac OpEx.java % java OpEx 1 2 1 1.0416666666666667 1.0416666666666667 /* * * The program deals with operators. * Comment not included. * @version $Id$ * * @author hp bischof * * Revisions: * $Log$ */ class OpEx { public static void main(String args[]) { int intVar_1 = 1; int intVar_2 = 2; int intRes = 3; double doubleVar_1 = 3.8; double doubleVar_2 = 4.8; double doubleRes = doubleVar_1 - doubleVar_2; intRes = 5 / 3; System.out.println(intRes); intRes = 5 % 3; System.out.println(intRes); // intRes = 5 / doubleVar_2); // Doesn't work, why? intRes = (int)(5 / doubleVar_2); System.out.println(intRes); doubleRes = 5 / doubleVar_2; System.out.println(doubleRes); doubleRes = 5.0 / doubleVar_2; System.out.println(doubleRes); } }
Assignment Operators • There are 12 assignment operators; all are syntactically right-associative (they group right-to-left). = *= /= %= += -= <<= >>= >>>= &= ^= |= • Note: We will ignore the second line for the moment. • The syntax for an assignemnt is: Assignmnet: LeftHandSide AssignmentOperator AssignmentExpression • LeftHandSide must be a variable • AssignmentOperator must be one of = *= /= %= += -= <<= >>= >>>= &= ^= |= • AssignmentExpression must be ConditionalExpression or Assignment • Note: A variable that is declared final cannot be assigned to.
Assignment Example • Result % javac Assignment.java % java Assignment 1 3 6 3 2 7 /** * The program deals with assignment and ++, -- operators. * Comment not included. * * @version $Id$ * * @author hp bischof * * Revisions: * $Log$ */ class Assignment { public static void main(String args[]) { int intVar_1 = 1; int intVar_2 = 1; int intRes; intRes = intVar_1++; System.out.println(intRes); intRes = ++intVar_1; System.out.println(intRes); intRes += intVar_1; System.out.println(intRes); intRes -= intVar_1; System.out.println(intRes); intRes = 4; intRes /= 2; System.out.println(intRes); intRes = ++intRes + ++intRes; System.out.println(intRes); } }
Math Class /** * The program handles is using the Math class. * * @version $Id$ * * @author hp bischof * * Revisions: * $Log$ */ import java.lang.Math.*; class MathTest { public static void main(String args[]) { int intId; System.out.println("pi = " + Math.PI ); System.out.println("sqrt(2.0) = " + Math.sqrt(2.0) ); System.out.println("abs(-3) = " + Math.abs(-3.0) ); intId = Math.min( 12, 2 ); System.out.println("intId = " + intId ); } } /** * The program handles is using the Math class. * * @version $Id$ * * @author hp bischof * * Revisions: * $Log$ */ import java.lang.Math.*; class MathTest { public static void main(String args[]) { int intId; System.out.println("pi = " + Math.PI ); System.out.println("sqrt(2.0) = " + Math.sqrt(2.0) ); System.out.println("abs(-3) = " + Math.abs(-3.0) ); intId = Math.min( 12, 2 ); System.out.println("intId = " + intId ); } }
Class Declarations • Class declarations define new reference types and describe how they are implemented. • Constructors are similar to methods, but cannot be invoked directly by a method call; they are used to initialize new class instances. Like methods, they may be overloaded. • Static initializers are blocks of executable code that may be used to help initialize a class when it is first loaded. • The body of a class declares members, static initializers, and constructors. The scope of the name of a member is the entire declaration of the class to which the member belongs. Field, method, and constructor declarations may include the access modifiers public, protected, or private. The members of a class include both declared and inherited members. Newly declared fields can hide fields declared in a superclass or superinterface. Newly declared methods can hide, implement, or override methods declared in a superclass. • Definition of a method: <visibility modifier> <return type> <method name> ( <parameters> ) { <statements> } • Example: public int getX() { ... return x; // x is a int variable } public void getX( int y) { ... x = y; } • visibility modifier: public/private • Return type: void/primitive type/reference to a object • Class methods/Class variables are declared with static. • Static declaration inside a method change the lifetime of a variable.
Lab 3 • String class • Object variable references • Null references and unassigned variables • Using member methods
String Class • The String class represents character strings. All string literals in Java programs, such as "abc", are implemented as instances of this class. • Strings are constant; their values cannot be changed after they are created. String buffers support mutable strings. Because String objects are immutable they can be shared.
String Example • Output: 4 17 0 34 o l l u /** * Play with the String class * @version $Id$ * @author Hpb * $Log$ */ import javabook.*; class String_1 { public static void main( String args[] ) { String w_1 = "oslo"; String w_2 = new String("ich glaub's nicht"); String w_3 = new String(); System.out.println(w_1.length()); System.out.println(w_2.length()); System.out.println(w_3.length()); System.out.println(w_2.concat(w_2).length()); System.out.println(w_1.charAt(0)); System.out.println(w_1.charAt(2)); System.out.println(w_1.substring(2,3)); System.out.println("Drum".substring(2,3)); } }
Palindrom checker • Output: -otto- = true -ich glaub's nicht- = false -a- = true -- = true /* * * Find's out if a word is a palindorm. * @version $Id$ * @author Hpb * Revisions: * $Log$ */ import javabook.*; class Palindrom { private static boolean palindrom(String w) { boolean res = true; for ( int index = 0; index < w.length(); index ++ ) { res = res && ( w.charAt(index) == w.charAt(w.length() - 1- index) ); } return res; } public static void main( String args[] ) { String w_1 = "otto"; String w_2 = new String("ich glaub's nicht"); String w_3 = new String("a"); String w_4 = new String(); System.out.println("-" + w_1 + "- = " + palindrom(w_1) ); System.out.println("-" + w_2 + "- = " + palindrom(w_2) ); System.out.println("-" + w_3 + "- = " + palindrom(w_3) ); System.out.println("-" + w_4 + "- = " + palindrom(w_3) ); } }
Lab 4 • Class design • Data abstraction • Information hiding • Instance variables • Accessor methods • Mutator methods • Constructors • Facilitator methods • Graphics.drawArc() and Graphics.fillArc() methods
Lab 5 • The if statement • Boolean logic • Truth tables • The switch statement • Comparing objects using equal()
Boolean Expressions • In order to write programs that solve any but the most elementary problems we need a way to make decisions. • In order to make decisions, we need to understand how to construct Boolean expressions. These are expressions that evaluate to one of two values, true or false.
Relational Operators • Simple Boolean expressions consist of comparing things using relational operators. There are two types of relational operators: equality and comparison. • Equality operators are defined for all objects and primitive types. • == equal • != not equal • For basic types these are the values and things work as expected. For reference types this just checks if they point to the same object. It does not check if the objects referenced have the same contents.
Logic Operators • These operators take Boolean arguments and return Boolean results. • They are used to construct complex Boolean expressions from simple ones consisting of Boolean values and relational expressions. • & and • && conditional and (short circuits) • | or • || conditional or (short circuits) • ^ xor • ! not (unary operator)/boolean complement • x && y y will be evaluated only if x is true • x || y y will be evaluated only if x if false
Truth Tables for Boolean Operators not | ------+-------- False | True True | False | | and | False True or | False True ------+---------------- ----------+-------------- False | False False False | False True True | False True True | True True | | | | xor | False True implies | False True ------+---------------- ----------+-------------- False | False True False | True True True | True False True | False True The left operand (``receiver'') is specified in the left column; the right operand (``argument'') is specified in the top row.
IfThen Statement • The if statement allows conditional execution of a statement or a conditional choice of two statements, executing one or the other but not both. • IfThen Statement: • if ( Expression ) Statement • Example: x = 3; y = 4; if ( x > y ) z = x;
IfThenElse Statement • IfThenElse Statement: if ( Expression ) Statement else Statement • Example: x = 3; y = 4; if ( x > y ) z = x; else z = y;
Find the Maximum of two Numbers I /** * Find the maximum of two numbers. * @version $Id$ * * @author Hpb * * Revisions: $Log$ */ import javabook.*; class Maximum { public static void main( String args[] ) { MainWindow win = new MainWindow("Maximum program"); InputBox input = new InputBox(win); OutputBox output = new OutputBox(win); double firstN = input.getFloat("Enter the first number:"); double secondN = input.getFloat("Enter the second number:"); double max; // the if then else part if ( firstN > secondN ) max = firstN; else max = secondN; output.show(); output.printLine("Maximum(" + firstN + ", " + secondN + ") = " + max); } }
Find the Maximum of two Numbers II /* * Find the maximum of two numbers. This program is using a class method. * * @version $Id$ * * @author Hpb * * Revisions: * $Log$ */ import javabook.*; class Maximum_2 { public static double maximum(double _first, double _second ) { double max; // find maximum if ( _first > _second ) max = _first; else max = _second; return max; } public static double minimum(double _first, double _second ) { double minimum; // find minimum if ( _first < _second ) minimum = _first; else minimum = _second; return minimum; } public static void main( String args[] ) { MainWindow win = new MainWindow("Maximum 2"); InputBox input = new InputBox(win); OutputBox output = new OutputBox(win); double firstN = input.getFloat("Enter the first number:"); double secondN = input.getFloat("Enter the second number:"); // win.show(); output.show(); output.printLine("Maximum(" + firstN + ", " + secondN + ") = " + maximum( firstN, secondN) ); output.printLine("Minimum(" + firstN + ", " + secondN + ") = " + minimum( firstN, secondN) ); } }