CSC 176: Introduction to Programming - PowerPoint PPT Presentation

1 / 78
About This Presentation
Title:

CSC 176: Introduction to Programming

Description:

Title: Development Lifecycle Models Author: lilliec Last modified by: UNCP Created Date: 6/25/2002 6:40:39 PM Document presentation format: On-screen Show – PowerPoint PPT presentation

Number of Views:92
Avg rating:3.0/5.0
Slides: 79
Provided by: lill2
Category:

less

Transcript and Presenter's Notes

Title: CSC 176: Introduction to Programming


1
CSC 176 Introduction to Programming
  • Fall 2005
  • Dr. Chuck Lillie

2
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

3
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

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

5
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

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

7
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

8
Problem Solving
Determine
Analysis
problem features
Rethink as
appropriate
Describe objects
Design
and methods
Produce the
Implementation
classes and code
Examine for
Testing
correctness
9
Problem Solving -- Problem Definition
  • A clear statement of the problem
  • Defines problem without any reference to solution
  • Should be in users language
  • Not in technical terms

Failure to define problem may cause you to solve
the wrong problem
10
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?

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

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

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

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

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

16
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
  • Dont be afraid to rebuild
  • Dont be afraid to try something new

17
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

18
Lab 2
  • Operator order of precedence
  • Declarations
  • Standard input stream
  • Expressing mathematical equations
  • Class methods

19
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 lt 5 left to right
  • less than or equal lt 5 left to right
  • greater than gt 5 left to right
  • greater than or equal gt 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

20
Object
  • An object is a structure that represents a state
    and knows methods to manipulate it. The structure
    components are called instance variables.

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

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

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

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

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

26
Character Example
  • /
  • This program is using the Character class
  • _at_version Id
  • _at_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")
  • Output
  • a a
  • Character.isDigit('a') false Character.isDigit('0
    ') true Character.isDigit('0') true
  • c_1 ! c_2
  • c_1.equal(c_2)

27
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.79E308 1.79E308

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

29
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

30
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

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

32
Casting Example
  • Results
  • javac OpEx.java
  • java OpEx
  • 1
  • 2
  • 1
  • 1.0416666666666667
  • 1.0416666666666667
  • /
  • The program deals with operators.
  • Comment not included.
  • _at_version Id
  • _at_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

33
Assignment Operators
  • There are 12 assignment operators all are
    syntactically right-associative (they group
    right-to-left).
  • / -
  • ltlt gtgt gtgtgt
  • 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
  • / - ltlt gtgt gtgtgt
  • AssignmentExpression must be ConditionalExpression
    or Assignment
  • Note A variable that is declared final cannot be
    assigned to.

34
Assignment Example
  • /
  • The program deals with assignment and , --
    operators.
  • Comment not included.
  • _at_version Id
  • _at_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)
  • Result
  • javac Assignment.java
  • java Assignment
  • 1
  • 3
  • 6
  • 3
  • 2
  • 7

35
Math Class
  • /
  • The program handles is using the Math class.
  • _at_version Id
  • _at_author hp bischof
  • Revisions
  • Log
  • /
  • import java.lang.Math.
  • class MathTest
  • public static void main(String args)
  • int intId

/ The program handles is using the Math
class. _at_version Id _at_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 )

36
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
  • ltvisibility modifiergt ltreturn typegt ltmethod
    namegt ( ltparametersgt ) ltstatementsgt
  • 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.

37
Lab 3
  • String class
  • Object variable references
  • Null references and unassigned variables
  • Using member methods

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

39
String Example
  • Output
  • 4
  • 17
  • 0
  • 34
  • o
  • l
  • l
  • u
  • /
  • Play with the String class
  • _at_version Id
  • _at_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))

40
Palindrom checker
  • /
  • Find's out if a word is a palindorm.
  • _at_version Id
  • _at_author Hpb
  • Revisions
  • Log
  • /
  • import javabook.
  • class Palindrom
  • private static boolean palindrom(String w)
  • boolean res true
  • for ( int index 0 index lt 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"
  • Output
  • -otto- true
  • -ich glaub's nicht- false
  • -a- true
  • -- true

41
Lab 4
  • Class design
  • Data abstraction
  • Information hiding
  • Instance variables
  • Accessor methods
  • Mutator methods
  • Constructors
  • Facilitator methods
  • Graphics.drawArc() and Graphics.fillArc() methods

42
Lab 5
  • The if statement
  • Boolean logic
  • Truth tables
  • The switch statement
  • Comparing objects using equal()

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

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

45
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

46
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.
47
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 gt y )
  • z x

48
IfThenElse Statement
  • IfThenElse Statement
  • if ( Expression )
  • Statement
  • else
  • Statement
  • Example
  • x 3
  • y 4
  • if ( x gt y )
  • z x
  • else z y

49
Find the Maximum of two Numbers I
  • /
  • Find the maximum of two numbers.
  • _at_version Id
  • _at_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

50
Find the Maximum of two Numbers II
  • /
  • Find the maximum of two numbers. This program is
    using a class method.
  • _at_version Id
  • _at_author Hpb
  • Revisions
  • Log
  • /
  • import javabook.
  • class Maximum_2
  • public static double maximum(double _first,
    double _second )
  • double max
  • // find maximum
  • if ( _first gt _second )
  • max _first
  • else max _second

51
Find the Maximum of two Numbers III
  • /
  • Find the maximum of two numbers.
  • This program is using a class method.
  • _at_version Id
  • _at_author Hpb
  • Revisions
  • Log
  • / import javabook.
  • class Maximum_3
  • public static double maximum(double _first,
    double _second )
  • if ( _first gt _second )
  • return _first
  • else
  • return _second

52
Switch Statement
  • The switch statement transfers control to one of
    several statements depending on the value of an
    expression. The type of the switch expression can
    be
  • --
  • char
  • --
  • byte
  • --
  • short
  • --
  • int
  • Switch Statement
  • switch ( Expression )
  • case ConstantExpression_1 action_1
  • case ConstantExpression_2 action_2
  • ...
  • default action_d

53
Switch Statement Example
  • class Many
  • static void howManyWithBreak(int k)
  • System.out.println(k "------------------")
  • switch (k)
  • case 1 System.out.println("with break one ")
  • break
  • case 2 System.out.println("with break too ")
  • break
  • default System.out.println("with break
    many")
  • static void howManyWithoutBreak(int k)
  • System.out.println(" " k "-----------------
    -")
  • switch (k)
  • case 1 System.out.println(" without break one
    ")
  • case 2 System.out.println(" without break too
    ")
  • default System.out.println(" without break
    many")
  • Execution
  • javac Many.java java Many
  • 3------------------ with break many
  • 2------------------ with break too
  • 1------------------ with break one
  • 3------------------ without break many
  • 2------------------ without break too
  • without break many
  • 1------------------ without break
  • one without break too
  • without break many

54
Partial Lowercase ? Uppercase
  • /
  • Test of the switch statement.
  • _at_version Id
  • _at_author hpb
  • Revisions
  • Log
  • /
  • import javabook.
  • class Switch_1
  • public static String itWasA(char c)
  • switch( c )
  • case 'a' return("A")
  • // break??
  • case 'b' return("B")
  • // break??

55
Lab 6
  • Looping
  • while statement
  • do while statement
  • for statement
  • File stream extraction

56
While Statement
  • The while statement executes an Expression and a
    Statement repeatedly until the value of the
    Expression is false.
  • While Statement
  • while ( Expression ) Statement
  • Example
  • x 1
  • while ( x lt 10 )
  • print x x 2

57
Abrupt Completion
  • Abrupt completion of the contained Statement is
    handled in the following manner
  • If execution of the Statement completes abruptly
    because of a break with no label, no further
    action is taken and the while statement completes
    normally.
  • If execution of the Statement completes abruptly
    because of a continue with no label, then the
    entire while statement is executed again.

58
Calculate Sqrt(2) without the MathClass
  • /
  • Calculate Sqrt(2) without the MathClass
  • _at_version Id
  • _at_author Hpb
  • Revisions
  • Log
  • /
  • import javabook.
  • class Sqrt
  • public static double calculateSqrt_2()
  • double n1 1.0
  • double n2 2.0
  • while ( (n2 n2 - n1 n1) gt 0.0001)
  • double x ( n2 n1 ) 0.5
  • if ( x x gt 2.0 )
  • n2 x
  • else n1 x

59
Do Statement
  • The do statement executes a Statement and an
    Expression repeatedly until the value of the
    Expression is false.
  • do Statement while ( Expression )

60
For Statement
  • The for statement executes some initialization
    code, then executes an Expression, a Statement,
    and some update code repeatedly until the value
    of the Expression is false.
  • For Statement
  • for ( ForInit Expression ForUpdate)
  • Statement
  • Example
  • for ( index 0 index lt 10 index )
  • System.out.println(index)
  • If the value of the Expression is false the first
    time it is evaluated, then the Statement is not
    executed.
  • If the Expression is not present, then the only
    way a for statement can complete normally is by
    use of a break statement.

61
Find all Prime Numbers in 2 ... 100
/ Find all prime numbers in the range
between 1 and 100. Improved version. This
program is using a class method. _at_version Id
_at_author Hpb Revisions Log / import
javabook. class Prime_2 public static
boolean isPrime(int n) if ( n 1 )
return false if ( n 2 ) return
true for ( int index 2 index lt n index
2 ) if ( n index 0 ) return
false return true public static
void main( String args ) MainWindow win
new MainWindow("Prime_1") OutputBox output
new OutputBox(win) output.show() for (
int index 2 index lt 100 index ) if (
isPrime(index) ) output.printLine(index " " )
  • /
  • Find all prime numbers in the range
  • between 1 and 100
  • This program is using a class method.
  • _at_version Id
  • _at_author Hpb
  • Revisions
  • Log
  • /
  • import javabook.
  • class Prime_1
  • public static boolean isPrime(int n)
  • for ( int index 2 index lt n index )
  • if ( n index 0 )
  • return false

62
Lab 7
  • Parameter passing
  • Methods inherited from Object
  • Overriding methods
  • static methods
  • java.util.Random class
  • Scope and name reuse

63
Parameter Passing
  • The formal parameters of a method, if any, are
    specified by a list of comma-separated parameter
    specifiers.
  • Each parameter specifier consists of a type and
    an identifier (optionally followed by brackets)
    that specifies the name of the parameter.
  • If a method has no parameters, only an empty pair
    of parentheses appears in the method's
    declaration.
  • If two formal parameters are declared to have the
    same name (that is, their declarations mention
    the same Identifier), then a compile-time error
    occurs.
  • When the method is invoked, the values of the
    actual argument expressions initialize newly
    created parameter variables,. each of the
    declared Type, before execution of the body of
    the method.
  • The scope of formal parameter names is the entire
    body of the method. These parameter names may not
    be redeclared as local variables or exception
    parameters within the method that is, hiding the
    name of a parameter is not permitted.

64
Example Use of a Point Class
  • public class TestPoint_1
  • private static Point_1 aPoint
  • public static void main(String args)
  • aPoint new Point_1(2, 3)
  • System.out.println("x " aPoint.getX() )
  • System.out.println("y " aPoint.getY() )
  • aPoint new Point_1()
  • aPoint.initPoint(4, 5)
  • System.out.println("x " aPoint.getX() )
  • System.out.println("y " aPoint.getY() )
  • aPoint.move(6, 7)
  • System.out.println("x " aPoint.getX() )
  • System.out.println("y " aPoint.getY() )
  • Execution of the test program
  • javac TestPoint_1.java Point.java java
    TestPoint_1
  • in Point() constructor
  • in Point(int, int) constructor
  • in getX()
  • x 2
  • in getY()
  • y 3
  • in Point() constructor
  • in initPoint(int, int)
  • in getX()
  • x 4
  • in getY()
  • y 5
  • in move(int, int)
  • in getX()
  • x 10
  • in getY()
  • y 12

65
Parameter Passing
  • Result
  • javac Param.java java Param
  • 1. main!intVariable 3
  • 2. intMethod!intArg 3
  • 3. intMethod!intArg 33
  • 4. main!intVariable 3
  • 5. main!intArray0 3
  • 6. intMethod!intArg0 3
  • 7. intMethod!intArg0 33
  • 8. main!intArray0 33
  • /
  • This program deals with parameter passing
  • _at_version Id
  • _at_author Hpb
  • Revisions
  • Log
  • /
  • class Param
  • public static void intMethod(int intArg)
  • System.out.println("\t 2. intMethod!intArg "
    intArg )
  • intArg 33
  • System.out.println("\t 3. intMethod!intArg "
    intArg )
  • public static void intArrayMethod(int intArg)
  • System.out.println("\t 6. intMethod!intArg0
    " intArg0 )
  • intArg0 33
  • System.out.println("\t 7. intMethod!intArg0
    " intArg0 )

66
Lab 8
  • One-dimensional arrays
  • Subscripting
  • Array manipulation
  • Searching techniques
  • Java collection framework
  • Iterators
  • ArrayList

67
Arrays
  • Java arrays are objects, are dynamically created,
    and may be assigned to variables of type Object.
    All methods of class Object may be invoked on an
    array.
  • An array object contains a number of variables.
    The number of variables may be zero, in which
    case the array is said to be empty. The variables
    contained in an array have no names instead they
    are referenced by array access expressions that
    use nonnegative integer index values. These
    variables are called the components of the array.
    If an array has n components, we say n is the
    length of the array the components of the array
    are referenced using integer indices from 0 to
    n-1, inclusive.
  • There is one situation in which an element of an
    array can be an array if the element type is
    Object, then some or all of the elements may be
    arrays, because any array object can be assigned
    to any variable of type Object.

68
Array Example
  • Result
  • javac A1java java Array_1
  • 15
  • /
  • This program is using an array.
  • It calculates the sum of the first n integers
  • _at_version Id
  • _at_author Hpb
  • Revisions
  • Log
  • /
  • class Array_1
  • public static void main(String args)
  • int ia new int6
  • int sum 0
  • for (int i 0 i lt ia.length i)
  • iai i
  • for (int i 0 i lt ia.length i)
  • sum iai
  • System.out.println(sum)

69
Array Example
  • Result
  • javac A2java java Array_2
  • monthName.length 12
  • 0 January
  • 1 February
  • 2 March
  • 3 April
  • 4 May
  • 5 June
  • 6 July
  • 7 August
  • 8 September
  • 9 October
  • 10 November
  • 11 December
  • /
  • This program is using an array.
  • It prints the name of each month.
  • _at_version Id
  • _at_author Hpb
  • Revisions
  • Log
  • /
  • class Array_2
  • public static void main(String args)
  • // StringmonthName new String12 or
  • StringmonthName "January", "February",
    "March", "April", "May", "June", "July",
  • "August", "September", "October", "November",
    "December"
  • System.out.println("monthName.length "
    monthName.length )
  • for (int i 0 i lt monthName.length i)
  • System.out.println(i " " monthNamei
    )

70
2 dimensional arrays
  • /
  • This program is using n dimensional arrays.
  • _at_version Id
  • _at_author Hpb
  • Revisions
  • Log
  • /
  • class Array_3
  • public static void main(String args)
  • int ia 1, 2, 3, 4
  • int iNew new int2020
  • int threeDim new int202020
  • for (int i 0 i lt 2 i)
  • for (int j 0 j lt 2 j)
  • System.out.println(iaij)
  • for (int i 0 i lt 20 i)
  • for (int j 0 j lt 20 j)
  • iNewij i j

71
Vector
  • The Vector class implements a growable array of
    objects. Like an array, it contains components
    that can be accessed using an integer index.
    However, the size of a Vector can grow or shrink
    as needed to accommodate adding and removing
    items after the Vector has been created.
  • Each vector tries to optimize storage management
    by maintaining a capacity and a
    capacityIncrement. The capacity is always at
    least as large as the vector size it is usually
    larger because as components are added to the
    vector, the vector's storage increases in chunks
    the size of capacityIncrement. An application can
    increase the capacity of a vector before
    inserting a large number of components this
    reduces the amount of incremental reallocation.

72
Vector Example
  • Results
  • javac Vector_1.java java Vector_1
  • Vector is empty
  • 12
  • December
  • March
  • /
  • This program is using an array.
  • It calculates the sum of the first n integers
  • _at_version Id
  • _at_author Hpb
  • Revisions
  • Log
  • /
  • import java.util.Vector
  • class Vector_1
  • public static void fillVector(Vector vector)
  • vector.addElement("January")
  • vector.addElement("February")
  • vector.addElement("March")
  • vector.addElement("April")
  • vector.addElement("May")
  • vector.addElement("June")
  • vector.addElement("July")

73
Selection Sort
  • Idea The selection sort works by finding the
    smallest number in the array and places it in the
    first position in the array. It then repeats the
    process of finding the smallest element, except
    this time it starts looking at the second
    position in the array, and places the smallest
    element in the second position. This process
    continues until the array is sorted.

74
Lab 9
  • Inheritance
  • Inheritance hierarchies
  • Polymorphism
  • abstract classes
  • protected access
  • Overriding inherited methods
  • Extending swing class
  • Overriding paintComponent()
  • Proper use of repaint()

75
Private, Protected, Public and Final
  • Private
  • A private class member or constructor is
    accessible only within the class body in which
    the member is declared and is not inherited by
    subclasses. In the example
  • class Point
  • Point()
  • setMasterID()
  • int x, y
  • private int ID
  • private static int masterID 0
  • private void setMasterID()
  • ID masterID
  • the private members ID, masterID, and setMasterID
    may be used only within the body of class Point.
  • Protected
  • A protected member or constructor of an object
    may be accessed from outside the package in which
    it is declared only by code that is responsible
    for the implementation of that object
  • Public
  • A public class member or constructor is
    accessible throughout the package where it is
    declared and from any other package that has
    access to the package in which it is declared.
    For example, in the compilation unit
  • public class Point

76
Lab 10
  • Throwable class hierarchy
  • Throwing exceptions
  • Exception propagation
  • try-catch blocks
  • Subclass exceptions
  • Finally

77
Lab 11
  • Using activation records to trace recursion
  • Mutual recursion
  • Recursive binary search

78
Lab 12
  • Timer class
  • TimerTask class
  • Fixed-rate vs. fixed-delay scheduling
  • Swing-based animation
  • Creating tasks at runtime
Write a Comment
User Comments (0)
About PowerShow.com