This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
• Control constructs– if (<exp>) <statement> [else <statement>]– while (<exp>) <statement>– do <statement> while (<exp>);– for (<exp>; <exp>; <exp>) <statement>
• Methods: parameter passing, signature line.• Declaring arrays, vectors, ArrayList, Initialization list• Classes: Inheritance (extends), Polymorphism (interface, abstract) • Input and output• Built in interfaces (Comparable, Iterator)
More Review from Programming I and Programming II
Good Programming Conventions
• Syntactical conventions– When and how much to indent– Reasonable identifier names– Single purpose methods without side-effects and reasonable size– Limit the scope of variables– Define class variables as high in the hierarchy as possible
• Common programming pitfalls– Comparing objects without equals() and compareTo()– Exceeding maximum numbers– Implicit type conversions (System.out.println(“ “+3+2);)
• Debugging techniques– Be structured, change one thing at a time– Don’t make changes without being sure why– Utilize available debugging tools (breakpoints, watch, step, prints)– Make use of assertion type statements
Exceptions
• How do programs handle exception?– Java try/catch exception handling
• Where should a program handle it?– Nowhere: program aborts– At point where exception occurs– Pass it up to a calling method (punt)
• Examples– Divide by zero– Decimal when integer expected– Trying to use a file that doesn't exist
Abnormal conditions arising while a program executes
Example with an Exceptionpublic double avg(int n){ int sum = 0; for (int k=1; k<=n; k++) sum += k; return sum / n;} // Question: What happens if n is zero?
public double avg(int n){ int sum = 0; if (n==0) { return 0; } for (int k=1; k<=n; k++) sum += k; return sum / n;}
Java Exception Handling
public double avg(int n){ int sum = 0; try { for (int k=1; k<=n; k++) sum += k; return sum / n; } catch (Exception e) { return 0; }}
Exception Handling AdvantageSeparates the error handling from the main flow of logic
– Example: InputStreamReader isr = new InputStreamReader(System.in);BufferedReader in = new BufferedReader(isr);
Flow of data from source to sink
Input and Handle Exceptions
double readDouble(double min, double max){ InputStreamReader isr=new InputStreamReader(System.in); BufferedReader in = new BufferedReader(isr); double value; while (true) { try { System.out.print("Enter a Double: "); value = Double.parseDouble(in.readLine());
if (value>=min && value<=max) return value; throw new NumberFormatException(); } catch (Exception ex) { System.out.println("Must be >="+min+" and <="+max); }} }
System.out.println( readDouble(5,10) );
Input with Scanner Classdouble readDouble(double min, double max){ Scanner scan = new Scanner (System.in);
double value; while (true) { try { System.out.print("Enter a Double: "); value = scan.nextDouble();
if (value>=min && value<=max) return value; throw new NumberFormatException(); } catch (Exception ex) { scan.next(); System.out.println("Must be >="+min+" and
<="+max); }} }
• Other Scanner methods– nextByte(), nextFloat(), nextLong(), nextInt(), nextBoolean(),
nextLine()
Example: What Prints?int value = 0; Scanner scan = new Scanner(System.in);for (int i=0; i<=4; i++){ try { value = scan.nextInt(); if (value%3==2) throw new NumberFormatException(); if (value>=1 && value<=3)
throw new IndexOutOfBoundsException(); value += 2; } catch (InputMismatchException ex) { value += 1; } catch (NumberFormatException ex) { value += 2; } catch (IndexOutOfBoundsException ex) { value += 3; } finally { value += 4; } System.out.println(value); scan.nextLine(); }
Assume: user respectively types 0, abc, 2, 3, and 4 as input. Recall: ‘%’ calculates remainder (i.e. 5%3 calculates 2).Answer: 6, 11, 8, 10, 10
String Tokenizer Class• Token: A group of characters treated as a unit.• StringTokenizer objects break a string into a set of tokens• Constructors
= new StringTokenizer(str, "i+-",true);– System.out.println(tokens.nextToken());– System.out.println(tokens.nextToken());– System.out.println(tokens.nextToken());– System.out.println(tokens.nextToken());– System.out.println(tokens.hasMoreTokens());
Keyboard.java
• We will use Keyboard.java in lab 2• The source is posted on our class web site• It provides general purpose keyboard input methods• It provides example code for
– Exception Handling– Practical use of the StringTokenizer class– Instantiation of a character stream for keyboard input– Uses data conversion methods– Provides “type ahead” input– Uses wrapper classes
A Java class using of exceptions and wrappers
Pseudo Code
• Acceptable Pseudo code must:– Enough detail so a competent programmer
could implement the algorithm– Not so much detail that it would be easier to
just look at the code
• Conventions– It should be language independent– Bold keywords such as: IF, WHILE, DO, etc.– Italicize variables– Use English like statements
A principle way of describing computer algorithms
Examples to follow
Lab 1 Complex Number Calculator• Adding complex numbers
– Add real to real, and imaginary to imaginary– Ex: 1+2i + 3+4i = (1+3) + (2+4)i = 4 + 6i
• Subtracting complex numbers– Negate signs and do an addition– Ex: 1+2i – (3+4i) = (1-3) + (2-4)i = -2 -2i
• Divide complex numbers– Multiply top and bottom by conjugate of denominator– Conjugate flips sign of imaginary part. Conjugate of 3+4i = 3-4i.– Ex: (1+2i)/(3+4i) = (1+2i)(3-4i) / ((3+4i)/(3-4i))
Initial Lab Assignment
Goals
• Become proficient with the StringTokenizer class• Implement a program requiring some tricky logic• Understand and use a parse tree in design
– A parse tree draws the paths through an algorithm as a diagram– We will illustrate this in class
• Practice describing program logic in pseudo code• Become familiar with exception handling in of Java• Perform I/O handling Exceptions appropriately
Note: http://java.sun.com/javase/reference/api.jsp is a good place for Java help