Download week01

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
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
Primitive data, Object, Reference, Alias
Class, Object, Inheritance, Polymorphism
Assignment, Widening conversion, Narrowing conversion
Constructor, Destructor, Garbage collection
Static method, Static variable, Instance variable
Private, Public, Protected
Method signature, Overloaded method, Formal and Actual
parameters, this, super
String, Concatenation, Escape sequence, white space
Byte code, Compiler, Interpreter
Pre-test, Post-test, and Counter controlled loops
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 (++,--,+,-,*,/,==,=,%,?,+=,*=)
• Primitive data types versus references to objects
– String compare, initialization, and concatenation.
– Aliases, null pointers, dangling references,
– Methods equals and compareTo
• Control constructs
– if (<exp>) <statement> [else <statement>]
– while (<exp>) <statement>
– do <statement> while (<exp>);
– for (<exp>; <exp>; <exp>) <statement>
• Methods: parameter passing, signature.
• Declaring arrays, Initialization list
• Classes: Inheritance (extends), Polymorphism via subclasses and
interfaces, abstract classes
• 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
• 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, variable values, step)
Make use of assertion statements
Exceptions
Abnormal conditions arising while a program executes
• How do programs handle an exception?
– Java try/catch syntax
• Where should a program handle it?
– Nowhere: program aborts
– At point where exception occurs
– Pass it up to a calling method (throw)
• 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
Throw 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;
}
// ArithmeticException – checked or
unchecked?
Checked Exceptions
From the API:
The class Exception and any subclasses that are not also
subclasses of RuntimeException are checked exceptions.
Checked exceptions need to be declared in a method or
constructor's throws clause if they can be thrown by the
execution of the method or constructor and propagate outside
the method or constructor boundary.
The compiler will give an error if you call a method or
constructor that throws a checked exception.
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 */ }
See demos/ED.java
Example Java Exceptions
There are many others
•
•
•
•
•
•
•
•
•
•
ArithmeticException
ArrayIndexOutOfBoundsException
StringIndexOutOfBoundsException
FileNotFoundException
IllegalArgumentException
IOException
NoSuchElementException
NullPointerException
NumberFormatException
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 if you need to.
Exception Hierarchy
•
•
•
•
•
•
Object
Throwable
Exception
RunTimeException
The various exceptions
Notes
– NumberFormatException inherits from
IllegalArgumentException
– Both StringIndexOutOfBoundsException and
ArrayIndexOutOfBoundsException inherit 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);
Try Self Test Exercises: 10.9, 10.10, and 10.11 in the Text (p. 602 (6th ed))
Answers to exercises at the end of the chapter.
Streams
Flow of data from source to sink
• 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);
• Wrapper Classes
– Class adding functionality to another class or primitive type
– Examples: BufferedReader, Integer
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)
{ 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
– 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 in the demos directory
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
– 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))
= ((1*3)-(2*(-4))+(1*(-4)+2*3)i) / ((3*3 - 4*(-4)) + (3*(-4)+4*3)i)
Initial Lab Assignment
Goals
• Become proficient with the StringTokenizer class
• Implement a program requiring some tricky logic
• Understand and construct a simple parser
– Given an ordered set of tokens, a parser:
• Determines whether the set is syntactically legal
• Takes appropriate actions for each token
– We will illustrate this in class
• Practice describing program logic in pseudo code
• Become familiar with exception handling in Java
• Handle I/O exceptions appropriately
Note: http://java.sun.com/javase/reference/api.jsp is a good place for Java help