Week 02 a - PowerPoint PPT Presentation

1 / 36
About This Presentation
Title:

Week 02 a

Description:

Placement of opening and closing braces for class and method definitions ... System.out.print(' and ' y.toString()); System.out.println(' = ' z.toString ... – PowerPoint PPT presentation

Number of Views:22
Avg rating:3.0/5.0
Slides: 37
Provided by: davidh67
Category:
Tags: class | week

less

Transcript and Presenter's Notes

Title: Week 02 a


1
Week 02 - a
  • Anatomy of a Program
  • The Math Class
  • Debugging

2
Sample Programs Referenced(code located in
course folder)
  • java floating.FloatFrame
  • java strings.StringLab
  • round vs. rint
  • MowTheLawn
  • BuggyPayroll
  • Base26 Arithmetic

3
Review from Lect01-b (AnimatedIllustrations)
  • java floating.FloatFrame
  • java strings.StringLab

4
Writing Java Code
  • Java syntax imposes some rules
  • Java is case-sensitive (camelNotation not same as
    CamelNotation)
  • Must put a semicolon at the end of each statement
  • Must balance parentheses and braces

5
Formatting Java Code
  • Programmer conventions make the code more
    readable but are not imposed by the compiler
  • White space (blank lines and spaces) is used to
    improve readability
  • Spaces between operands and operators
  • Leading spaces for indentation to show blocks
  • Blank lines between methods
  • Line breaks
  • are not required, but should be used, at the end
    of each statement
  • may occur in the middle of a statement but not in
    the middle of an identifier

6
Formatting Blocks of Java Code
  • Placement of opening and closing braces for class
    and method definitions
  • Comments at end of classes and methods
  • public class Sample
  • private int y
  • public int doubleIt()
  • return 2y
  • // end of doubleIt method
  • // end of Sample class

7
Identifiers
  • Name of a data field, method, class or object
  • Specified in declaration statements and headers
  • Rules
  • Should begin with a letter
  • Can contain letters, digits, underscores
  • Must not be a reserved word (e.g. class)
  • see Table 2.8, page 81 of text
  • Can be any length
  • Some examples of valid and invalid identifiers
  • Valid xrayVision, p28, TAX_RATE
  • Invalid TAX-RATE, p.28, File5

8
Naming Conventions
  • Class names start with capital letter
  • e.g. Washer
  • Other identifier names start with lowercase
    letter
  • e.g. inner
  • Each following word in the name starts with a
    capital letter (soCalledCamelNotation)
  • e.g. inRadius
  • Identifiers for constants (final) use all caps
    with underscores to separate words
  • e.g. FEET_PER_MILE

9
Comments
  • Comments are for the human reader
  • Program Maintenance
  • Single line comments start with //
  • // Create a Washer object
  • Multi-line comments are surrounded by / ... /
  • /
  • WasherApp.java Authors Koffman Wolz
  • A class that finds the weight of a batch of
  • flat washers
  • /

10
CSc-037 HW Comments(from Grading Sheet)
  • Class Comments / CSc-037 HW Assignment __
    ltone-line description of classgt   _at_author  Joe
    Schmoe _at_version ___/___/2005
  • Method Comments/ ltone-line description of
    purpose of methodgt  _at_param ltone-line
    description of each parametergt _at_return
    ltone-line description of returned valuegt
  • Prompts for All Input (use InputDialogs for now)
  • Headings/Labels on All Output
  • Comment after each    // end of
    ltdescription of blockgt
  • Comment line for each 10-15 line block of code
  • Meaningful CONSTANT, variable NamesMeaningful
    method Class Names
  • Indent 2 spaces for sub-blocks, 4 spaces for
    continuation of statement onto a second line

11
The main Method(in Client Class--"Application")
  • public static void main(String args)
  • // end of main method
  • public --
  • static --
  • void --
  • main --
  • String --
  • args --

12
Problem AnalysisReview
  • Input value(s)?
  • Output value(s)?
  • Known Constants Needed? (e.g. PI)
  • Classes (Methods)?
  • Existing
  • New
  • Algorithm?

13
Finding Existing MethodsThe Math Class
  • Java includes the Math class with methods for
    performing common functions
  • E.g. sqrt, sin, cos, round, random
  • No objects of class Math can be instantiated
  • Technical term is "static"
  • Methods are called using the class name
  • Examples
  • double diagonalSquare Math.sqrt( 2 side
    side )
  • int wholeNum Math.round(diagonalSquare)
  • int randNum (int) (Math.random()10) 1

14
BlueJ "Tools"gtUse Library Class
  • See list of available methods
  • Try Math
  • min
  • sqrt

15
Methods of the Math Class
  • See Table 2.11 of the text, page 87
  • Check the data types expected as arguments
  • Check the data types of the return values
  • Note Methods round and rint both round a double
    argument. round returns an int while rint
    returns a double
  • Why is this important? What is the value of y?
  • // Math.PI 3.14159
  • y Math.round(Math.PI 100) / 100
  • ---- or ----
  • y Math.rint(Math.PI 100) / 100
  • Try this in BlueJ Code Pad

16
Sample Programming Process
  • How long will it take to Mow the Lawn?
  • Inputs?
  • house dimensions, yard dimensions
  • Outputs?
  • time to mow lawn
  • Classes (Methods)?
  • Rectangle (area)
  • Lawn (setSize, getMowingTime)
  • Constants? (rate of mowing2.3 sq. meters/sec)
  • Algorithm?
  • ASS U ME yard and house are rectangular!
  • Try on paper/board
  • Write and test together using BlueJ

17
Client (Main Program)
  • import javax.swing.
  • public class MowTheLawn
  • public static void main(String args)
  • Rectangle yard, house
  • Lawn grass new Lawn()
  • String yardDimensions JOptionPane.showInputD
    ialog(
  • "Yard length, width (in
    meters)?")
  • yard new Rectangle(yardDimensions)
  • String houseDimensions JOptionPane.showInput
    Dialog(
  • "House length, width (in
    meters)?")
  • house new Rectangle(houseDimensions)
  • grass.setSize(yard.area() - house.area())
  • JOptionPane.showMessageDialog(null,grass.getMo
    wingTime()
  • " seconds to
    mow the lawn")
  • // end of main method
  • // end of MowTheLawn class
  • Question What attributes does a Rectangle need?
  • Question How will Rectangle get numeric length
    and width from the String?

18
Rectangle Class
  • public class Rectangle
  • private double length, width // dimensions of
    the Rectangle
  • public Rectangle(String dimensions) //
    Constructor
  • int len dimensions.length()
  • int comma dimensions.indexOf(",")
  • length Double.parseDouble(dimensions.substri
    ng(0,comma))
  • width Double.parseDouble(dimensions.su
    bstring(comma1,len))
  • // end of Rectangle constructor
  • public double area()
  • return length width
  • // end of area method
  • // end of Rectangle class

19
Lawn Class
  • public class Lawn
  • private double size
  • private final double MOWING_SPEED 2.3
  • public void setSize(double newSize)
  • size newSize
  • // end of setSize method
  • public double getMowingTime()
  • return size / MOWING_SPEED
  • // end of getMowingTime method
  • // end of Lawn class

20
How Do We KnowThat It Worked???
  • Program Testing
  • Test Data
  • Compare with results computed by hand

21
To the Computers...
  • View BlueJ Code Pad
  • (need to create/open a project to activate Code
    Pad)
  • Math.round(4.4)
  • Math.round(4.6)
  • Math.rint(4.4)
  • Math.rint(4.6)
  • Try BlueJ access to Library Methods
  • Look at Documentation for String and Math

22
Java BREAK
23
Common Errors and Debugging
  • Syntax errors
  • What is a syntax error?
  • When do we find out that our program has a syntax
    error or errors?
  • What common syntax errors did we explore in lab?
  • Others not explored?
  • Run-Time errors
  • Detected during the execution of a program
  • Examples division by 0, Double.parseDouble(non-nu
    mber)
  • Logic errors
  • Occur when the program is written from an
    incorrect algorithm
  • Example printing the result of a computation
    before the computation is performed.

24
Trace the Executionof the Program
  • Follow the statements in the order they would be
    executed.
  • What happens when a call to a method is reached?
  • By Hand Draw pictures of the contents of memory
    as the execution proceeds.
  • Primitives and objects
  • Parameters and local variables
  • Use System.out.println statements
  • Use the BlueJ debugger to step through the
    program execution.

25
Buggy Payroll Program
  • The term bug was coined by Admiral Grace Hopper
    in the early days of computers (1950s)
  • Nanosecond Story
  • Program has at least three logic errors
  • Usually you wont know a priori that there are
    errors
  • We need to first test the program to find the
    errors!

26
Testing
  • Standard Rate of Pay is 10/hour
  • Standard Tax Rate is 30
  • Check to be printed using
    FirstName LastName
  • Test Data
  • Einstein, Al (stored like this so sort works)
  • 40 hours
  • Output should be Al Einstein and 280

27
Payroll Client
  • import javax.swing.
  • public class BuggyPayroll
  • public static void main(String args)
  • String name JOptionPane.showInputDialo
    g( "Employee Name?")
  • double hoursWorked Double.parseDouble(
    JOptionPane.showInputDialog(
    "Hours?"))
  • Employee worker new Employee(name)
  • worker.printPayCheck(hoursWorked)
  • // end of main method
  • // end of BuggyPayroll class

28
Debugging
  • Use BlueJ debug tracing
  • Project View menu -- show Debugger
  • Click line number to add breakpoint
  • Step thru program

29
Printing Dollars Cents
  • We will discuss Formatting of numbers next time

30
Base-26 Arithmetic
  • Need 26 distinct digits
  • Just happen to be 26 letters in alphabet
  • Use A for zero, B for one, etc.
  • Client program to create a couple of base-26
    numbers, print out their sum
  • Our example will deal with 3-digit base-26 numbers

31
Base26Client
  • public class Base26Client
  • public static void main(String args)
  • Base26 x, y, z
  • x new Base26("BBC")
  • y new Base26("CBS")
  • z x.add(y)
  • System.out.print("Sum of " x.toString())
  • System.out.print(" and " y.toString())
  • System.out.println(" " z.toString())
  • // end main method
  • // end of Base26Client
  • Note Need to decide how to store attributes of
    object of type Base26

32
Base26 Class
  • public class Base26
  • private char ch26_2, ch26_1, ch26_0 //
    attributes of objects of type Base26
  • public Base26(String str3)
  • ch26_2 (char)(str3.charAt(0) - 'A')
  • ch26_1 (char)(str3.charAt(1) - 'A')
  • ch26_0 (char)(str3.charAt(2) - 'A')
  • // end of Base26 constructor
  • public Base26 add(Base26 arg)
  • int first, second
  • first 2626 ch26_2 26 ch26_1
    ch26_0
  • second 2626arg.ch26_2 26arg.ch26_1
    arg.ch26_0
  • int sum first second
  • String result "" (char)(sum/26/26'A')
  • (char)(sum/2626'A')
  • (char)(sum 26'A')
  • return new Base26(result)
  • // end of add method
  • public String toString()
  • String result "" (char)(ch26_2'A')

33
What Might Go Wrongwith Base26 Class?
  • Construct Invalid Number
  • fewer or more than 3-letter number
  • invalid characters
  • Overflow (more than 3-letter sum)
  • ZZZ AAB BAAA
  • More on "throwing" exceptions later

34
HW Assignment 2
  • Two parts
  • Problem 9, page 103
  • Problem 5, page 178
  • Turn in Together
  • staple all .java files to same Grading Sheet
  • Grading Sheet is Available on Course Web Site
    (Homework Page)

35
To the Computers...
  • Base26 Arithmetic
  • Drag from course folder to "My Documents"
  • Try other values
  • Run with BlueJ Debugger turned ON
  • Step through program to be sure you understand
    how it works

36
Java BREAK
Write a Comment
User Comments (0)
About PowerShow.com