odds and ends. cs 21a 09/18/05 l14: odds & ends slide 2 copyright © 2005, by the authors of...
TRANSCRIPT
Odds and Ends
L14: Odds & EndsSlide 2
Copyright © 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved
CS 21a09/18/05
Odds and Ends
Some small topics on the side … Basic Exception Handling Class variables (static methods and fields) Command-line arguments Input through JOptionPane
Exceptions
L14: Odds & EndsSlide 4
Copyright © 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved
CS 21a09/18/05
Basic Exception Handling Exception: something unexpected that
can occur in the execution of a program wrong number format NullPointerException ArrayIndexOutOfBoundsException divide by zero attempt to open a file that does not exist etc.
Java provides a way to handle exceptions that are thrown: the try-catch statement
L14: Odds & EndsSlide 5
Copyright © 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved
CS 21a09/18/05
Try-catch Statement
Syntax:try { … } catch ( Exception e ) { ... }
Example:try { System.out.println( 5 / x );} catch ( Exception e ) { System.out.println( “div by zero” );}
Note the formatti
ng conventi
on.
L14: Odds & EndsSlide 6
Copyright © 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved
CS 21a09/18/05
Breaking out of the try Block
try
{
statement1;
statement2; // if exception occurs here,
// statement3 will be skipped
statement3;
}
catch ( Exception e )
{
statement4; // executed after exception occurs
}
L14: Odds & EndsSlide 7
Copyright © 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved
CS 21a09/18/05
Try-catch Chaintry { … file operation …}catch( FileNotFoundException se ) { … if file is not found …}catch( EOFException ee ){ … if no more data to read …}catch( IOException e ){ … for all other cases not yet
covered …}…
you can catch “Exception” to catch any kind of Exception works because of
polymorphism
OR … You can use a “try-catch chain” to catch specific exceptions
L14: Odds & EndsSlide 8
Copyright © 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved
CS 21a09/18/05
Ignoring exceptions Some exceptions do not need to be caught but
will generate a runtime error if they occur Examples: NullPointerException,
ArrayIndexOutOfBoundsException If enclosed in a try-catch statement, users can
choose to handle them Other exceptions need to be caught
Examples: when dealing with Input/Output You may either: enclose the statements in a try-
catch statement and handle the situation or place the clause throws Exception at the end of the method header (recall console.readLine() example)
L14: Odds & EndsSlide 9
Copyright © 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved
CS 21a09/18/05
More on Exceptions (CS 21b)
Stuff we’ll discuss in more detail in CS 21b Different types of Exceptions Generating your own exceptions Other features
Don’t worry about these for now!
Class (static) variables and methods
L14: Odds & EndsSlide 11
Copyright © 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved
CS 21a09/18/05
Class (static) fields and methods
Things we’ve seen, but not fully explained Built-in Constants
Math.PI, FlowLayout.CENTER, Color.green, etc. Built-in functions
Math.sqrt(), Math.abs(), Integer.parseInt(), Double.isNaN()
Static methods public static void main( String[] args )
Static fields your own constants
public static final int MY_CONSTANT
These are all “static” fields or methods
L14: Odds & EndsSlide 12
Copyright © 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved
CS 21a09/18/05
Static Fields
means that the field is shared by all instances of the same class
aka “class variable” as opposed to “instance variable”
e.g., in BankAccount, balance is an “instance
variable” – each instance has its own independent copy
However, if all BankAccounts share a minimum balance value, we can make a static field for that
L14: Odds & EndsSlide 13
Copyright © 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved
CS 21a09/18/05
Example: Minimum Balance
Account
SV129
Account
SV506
Account
SV008
balance balance balance908.55 1304.98 354.00
Account
minBalance
100.00
There is one copy of minBalance for the whole class and shared by all instances.
There is one copy of minBalance for the whole class and shared by all instances.
The Accountclass
instances of the Account class
L14: Odds & EndsSlide 14
Copyright © 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved
CS 21a09/18/05
Static Methods
Normally, a method applies to a particular instance e.g., you can’t just call deposit() from an applet.
(Which account are you deposting to?) you have to call aliceAccount.deposit(),
where aliceAccount is a pre-existing BankAccount a static method is a method that does not refer to a
particular instance That’s why we call them using ClassName.methodName()
there’s no instance that “owns” it. It “belongs” to the class in BlueJ, we right-click on the class, not on the instances
Useful for “functions” that don’t depend on an instance e.g., Math.sqrt( double d )
Note: they cannot refer to instance variables can only use static fields and methods that’s why convenience methods used by main have to be
static
L14: Odds & EndsSlide 15
Copyright © 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved
CS 21a09/18/05
public class BankAccount{ private static int curNum = 0; private int balance;
public BankAccount( int initBal ) { balance = initBal; BankAccount.curnum++; } public void deposit( int amount ) { balance += amount; } public void withdraw( int amount ) { balance -= amount; } public int getBalance() { return balance; }}
Another example In this code, we use
the static field curNum to keep track of the number of BankAccounts created.
Whenever we create a bank account, the value of curNum increases by 1.
CurNum is accessible by all instances of BankAccount
Command-Line Arguments
L14: Odds & EndsSlide 17
Copyright © 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved
CS 21a09/18/05
Using command-line arguments
Arguments entered from the command line e.g. java InputSampler abc 123
“abc” and “123” are command-line arguments
public static void main( String[] args ) String[] args stores these arguments args.length = 0 if no arguments are entered args.length = 2 if you run the example above
Usage String x = args[0]; //if args.length > 0
L14: Odds & EndsSlide 18
Copyright © 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved
CS 21a09/18/05
Using command-line arguments
Very easy and straightforward to use. No need to include classes.
Only takes in Strings. You will need to convert to ints or doubles, if needed.
Works only if you put in command-line arguments. Otherwise, you get an ArrayIndexOutOfBounds exception if you try to access an index that does not exist. Hence, the need to check for the length of the array.
JOptionPane
L14: Odds & EndsSlide 20
Copyright © 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved
CS 21a09/18/05
Using JOptionPane
import javax.swing.*; String showInputDialog( String prompt
) Usage:
String x = JOptionPane.showInputDialog( “Enter string: ” );
L14: Odds & EndsSlide 21
Copyright © 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved
CS 21a09/18/05
Using JOptionPane
Provides a nice GUI window for user to provide input, when in a Java application
Need to import javax.swing to use it Only takes in Strings. You will need to
convert to ints or doubles, if needed.
Need to call System.exit( 0 ); at the last line of main() so that the program exits