Transcript Document

Procedural programming in Java
Example 1 :public class Program1 {
public static void main(String [] args) {
int value1, value2, sum;
value1 = Integer.parseInt(args[0]);
value2 = Integer.parseInt(args[1]);
sum = value1 + value2;
System.out.println(“Sum is “ + sum);
} //end main
} //end class Program3
Handling integer
values
Integers of type - long, int
short or byte.
Variable declaration.
Variables start with small
letter.
Integer.parseInt converts
strings to numbers.
Assignment statement
Number automatically
converted back to string
for display.
Procedural programming in Java
Command-line arguments
Determining number of arguments
int numberOfArgs = args.length; //Note - no brackets
For any array, arrayName.length gives length
Conversion to integer
int value = Integer.parseInt(args[0]);
parseInt() raises NumberFormatException if a non numeric
value is entered.
Conversion to float
double volume = Double.parseDouble(args[1]);
Again this can raise NumberFormatException
try {
Dealing with
value = Integer.parseInt(args[0]);
exceptions
} //end try
catch(NumberFormatException nfe){
System.err(“Argument should be an integer”);
System.exit(-1);
} //end catch
Procedural programming in Java
public class Program2 {
public static void main(String [] args) {
int value1, value2, sum; //declare variables
Revised version
if ( args.length != 2 ) {
of addition
System.err(“Incorrect number of arguments”);
System.exit(-1);
program.
} //end if
try {
//attempt to convert args to integers
Checks number
value1 = Integer.parseInt(args[0]);
of arguments
value2 = Integer.parseInt(args[1]);
} //end try
catch(NumberFormatException nfe) {
Checks that
System.err(“Arguments must be integers”);
arguments are
System.exit(-1);
numbers.
} //end catch
sum = value1 + value2;
System.out.println(“Sum is “ + sum);
} //end main
} //end class Program3
Procedural Programming in Java
Prompted keyboard input
So far we have obtained program input from the command line arguments.
This limits us to only a few values and we are unable to prompt the user.
The usual way of getting input is to issue a prompt and then receive data from
the keyboard within the program as follows :import java.io.*; //provides visibility of io facilities
public class Greeting {
public static void main(String [] args) throws IOException {
String name;
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader in = new BufferedReader(isr);
System.out.print(“Enter your name : “); //prompt for input
name = in.readLine();
//get it
System.out.println(“Welcome to Java - “ + name);
} //end main
} //end class Greeting
Procedural Programming in Java
Prompted keyboard input
Input operations can cause run-time exceptions. The previous program chose
not to catch them but to propogate them out of main - hence the throws
IOException clause. Here, we catch such exceptions within the program.
import java.io.*; //provides visibility of io facilities
public class Greeting {
public static void main(String [] args) {
String name;
try {
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader in = new BufferedReader(isr);
System.out.print(“Enter your name : “); //prompt for input
name = in.readLine();
//get it
} //end try
catch(IOException ioe){}
System.out.println(“Welcome to Java - “ + name);
} //end main
} //end class Greeting
Procedural Programming in Java
Numeric input
Data is input as strings - just as with command-line input. If numeric input is
needed, explicit
import java.io.*; //provides visibility of io facilities
conversion is
public class Greeting {
required with
public static void main(String [] args) throws IOException {
Integer.parseInt()
String line;
int age;
boolean ok = false;
or
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader in = new BufferedReader(isr);
Double.parseDouble()
while (!ok) {
try {
System.out.print(“Enter your age : “); //prompt for input
line = in.readLine();
//get string
age = Integer.parseInt();
ok = true;
} //end try
catch(NumberFormatException nfe){
System.err.println(“Integer value required”);
} //end catch
} //end while
System.out.println(“You are “ + age + “ years old”);
} //end main
} //end class Greeting
Procedural Programming in Java
A useful method
//method to prompt for and get int value in specified range
public static int getInt(String prompt, int min, int max) {
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader in = new BufferedReader(isr);
boolean ok = false;
int result = 0;
while (!ok) {
try {
System.out.print(prompt); //prompt for input
result = Integer.parseInt( in.readLine() ); //get & convert it
if (result >= min && result <= max)
ok = true;
else
System.err.println(“Value must be between “ + min + “ and “ + max);
} //end try
catch(NumberFormatException nfe){
System.err.println(“Integer value required”);
} //end catch
catch(IOException e){}
} //end while
return result;
} //end getInt
Procedural Programming in Java
Reading text files
Note :File not found excep.
Should be handled.
Any number of files
may be open at once.
Can use a constant
string or variable to
name file.
Should close file at end
of program.
import java.io.*;
public class FileReadDemo {
public static void main(String [] args) throws IOException {
FileReader fr = null;
try {
fr = new FileReader(args[0]);
} //end try
catch(FileNotFoundException fnf){
System.err.println(“File does not exist”);
System.exit(-1);
} //end catch
BufferedReader inFile = new BufferedReader(fr);
String line;
while (inFile.ready()){
line = inFile.readLine();
System.out.println(line);
} //end while
inFile.close();
} //end main
} //end class FileReadDemo
Procedural Programming in Java
Writing text files
Note :Text output to file uses same commands - print & println as
screen output.
Must call flush() and close() to ensure data is written to file.
import java.io.*;
public class FileWriteDemo {
public static void main(String [] args) throws IOException {
FileOutputStream fos = new FileOutputStream(args[0]);
PrintWriter pr = new PrintWriter(fos);
for ( int i = 0; i < 20; i++)
pr.println(“Demonstration of writing a text file”);
pr.flush();
pr.close();
} //end main
} //end class FileWriteDemo
Programming in Java - Exception handling
Exceptions are run-time errors which occur under exceptional
circumstances - i.e. should not normally happen.
In Java an exception is an instance of an Exception class which
is thrown by the offending code.
Exceptions, if not handled by the program will cause the
program to crash.
Exceptions are handled by catching them and dealing with the
problem.
Exceptions are propogated from a method to the caller back
through the chain of callee to caller.
If propogated out of main, they are always handled by the run
time system. (virtual machine).
Programming in Java - Exception handling
Exceptions are of different types and form a class heirarchy, just as other
classes do.
Any number of catch
methods may follow a
try block.
public void methodA(){
//safe code
try {
//start of try block
//any number of statements
When an exception
//that could lead to an exception
occurs, these are scanned } //end try block
catch(InterruptedException ie){
in order, to find a
//code to deal with an IinterruptedException
matching parameter.
} //end catch
catch(IOException ioe){
If one is found, the
//code to deal with an IOException
exception is cancelled
}// end catch
and the handler code
catch(Exception e){
executed.
//code to deal with any Exception
}//end catch
//further code
All other catch methods
} //end methodA
are ignored.
Programming in Java - Exception handling
Exceptions are instances just like other class instances and can have
attributes and methods. This allows us to interrogate an exception
object to find out what
happened.
The exception class is a
sub-class of Throwable,
which provides the method
printStackTrace() etc.
The finally block following
a try block is always
executed.
Users may create their
own exceptions which
they can throw and
handle in same way as
predefined ones.
public void methodA(){
//safe code
try {
//start of try block
//any number of statements
//that could lead to an exception
} //end try block
catch(IOException ioe) {
ioe.printStackTrace();
System.out.println(“Exception handled”);
}//end catch
finally { //start finally block
//code always executed after we leave the
//try block regardless of what else happens
}//end finally block
//further code
} //end methodA
Programming in Java - Exception handling
public class GarageFull extends Exception {
private int capacity;
public GarageFull(int s){
capacity = s;
}//end GarageFull
public int getCapacity(){
return capacity;
}//end getCapacity
} //end class GarageFull
User-defined exceptions
public class Garage {
private Vehicle[] fleet = new Vehicle[100];
private int count = 0;
public void addVehicle(Vehicle v) throws GarageFull {
if (count =fleet.length)
throw new GarageFull(count);
else
fleet[count++] = v;
}//end add Vehicle
try {
myGarage.addVehicle(new Car(“ABC123”,4));
} //end try
catch(GarageFull gf){
System.err.println(“Operation failed”);
System.err.println(“Capacity is “ + gf.getCapacity());
} //end catch
Programming in Java - Exception handling
Exception classes fall into two groups - sub-classes of RunTimeException
and others. In the case of others :-
A method which could give
rise to an exception either
by throwing it or calling
a method which might,
must declare the fact in a
throws clause, or
handle the exception
locally.
Object
This does not apply to
RunTimeExceptions.
Throwable
Exception
InterruptedException
IOException
IndexOutOfBoundsException
RunTimeException
ArithmeticException
ParseException
NullPointerException
ArithmeticException
Programming in Java - Exception handling
public String getMessage() { //handles exception internally
String msg;
boolean ok = false;
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader in = new BufferedReader(isr);
System.out.println(“Enter message “);
while (!ok){
try {
msg = in.readLine();
ok = true;
} //end try
catch(IOException ioe){
System.err.println(“Try again”);
}//end catch
public String getMessage() throws IOException { //does not
}//end while
String msg;
return msg;
} //end GetMessage InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader in = new BufferedReader(isr);
System.out.println(“Enter message “);
msg = in.readLine();
return msg;
} //end GetMessage