Week 1 Power Point Slides

advertisement
Review of Terminology
These are terms taught in Programming I and Programming II
This list provides a list of terms to review
•
•
•
•
•
•
•
•
•
•
•
•
•
•
Variable, Constant, Identifier, Reserved word, Scope, Case sensitive
Operator, Precedence, Cast
Array, Vector
Primitive data, Object, Reference, Alias
Class, Object, Inheritance, Polymorphism
Assignment, Widening, Narrowing
Constructor, Destructor, Garbage collection
Static method, Static variable, Instance variable
Private, Public, Protected
Method signature, Overloading, Formal, Actual, this, super
String, Concatenation, Escape sequence, white space
Byte code, Applet, Compiler, Interpreter
Pre-test, Post-test, Counter controlled
Boolean, Block statement, condition
Review of Java Constructions
More Review from Programming I and Programming II
• Using the Java Class Library
– E.g.: Random, StringTokenizer, System, DecimalFormat, Math
• Operators (++,--,+,-,*,==,=,%,?,+=,*=, etc.)
• Primitive data types versus reference objects
– String compare, initialization, and concatenation.
– Aliases, null pointers, dangling references, equals, compareTo
• 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)
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
Abnormal conditions arising while a program executes
• 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
Example with an Exception
public 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
Handle where it occurs
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 Advantage
Separates the error handling from the main flow of logic
Punt Exception to Calling Method
public double avg(int n)
throws ArithmeticException
{ int sum = 0;
for (int k=1; k<=n; k++) sum += k;
return sum / n;
}
Syntax
try
{ // Attempt to execute these statements
}
catch (ExceptionName1 en1) {/* handling code */ }
catch (ExceptionName2 en2) {/* handling code */ }
.
.
.
catch (ExceptionNamek enk) {// handling code }
finally { /* this code always executes */ }
Example Java Exceptions
There are many others
•
•
•
•
•
•
•
•
•
•
ArithmeticException
ArrayIndexOutOfBoundsException
FileNotFoundException
IllegalArgumentException
IOException
NoSuchElementException
NullPointerException
NumberFormatException
StringIndexOutOfBoundsException
TypeMismatchException
Creating your own Exceptions
public class MyException extends Exception
{ public MyException()
{ super("MyException");
// Special exception handling logic
}
}
Sometimes Java doesn't have a suitable exception for
your purposes. You can create your own.
Exception Hierarchy
•
•
•
•
•
•
Object
Throwable
Exception
RunTimeException
The various exceptions
Notes
– NumberFormatException descends from
IllegalArgumentException
– ArrayIndexOutOfBoundsException and
StringIndexOutOfBoundsException descends from
IndexOutOfBoundsException
Which Exceptions are Thrown?
•
•
•
•
•
Integer.parseInt("26.2");
String s; s.indexOf('a');
String s = "hello"; s.charAt(5);
String s[] = new String[5]; s[5] = "hello";
StringTokenizer t = new StringTokenizer("");
System.out.println(t.nextToken());
• Int x = 0; int y=3; System.out.println(y/x);
How could you recover from an ArrayIndexOutOfBoundsException?
Try Exercise: 10.9, 10.10, and 10.11 in the Text
Streams
Flow of data from source to sink
• Wrappers
– Class adding functionality to another class or primitive type
– Examples: BufferedReader, Integer
• Built-in streams (System.in, System.out, System.err)
– Categories
• Character vs. byte,
• Process vs. data (to filter)
• Receive vs. send
– Example:
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader in = new BufferedReader(isr);
Input and Handle Exceptions
System.out.println( readDouble(5,10) );
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); }
} }
Input with Scanner Class
double 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)
{ 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
– StringTokenizer(String s)
– StringTokenizer(String s, String dilims)
– StringTokenizer(String s, String dilims, boolean b)
• Methods
– hasMoreTokens(), nextToken()
• Example:
– String str = “300 + 4.2i”.replaceAll(“\\s+” , “”); // eliminate white space
– StringTokenizer tokens
= 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
A Java class using of exceptions and wrappers
•
•
•
•
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
Pseudo Code
A principle way of describing computer algorithms
• 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
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
• Multiply complex numbers
– Real part = real1 * real2 – imaginary1 * imaginary2
– Imaginary part = real1*imaginary2 + imaginary1*real2
– Ex: (1+2i)*(3+4i) = (1*3-2*4) + (1*4 + 2*3)i = -5 + 10i
• 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
Download