150 likes | 289 Views
Procedural programming in Java. 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;
E N D
Procedural programming in Java 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 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. Example 1 :- Handling integer values
Procedural programming in Java try { value = Integer.parseInt(args[0]); } //end try catch(NumberFormatException nfe){ System.err(“Argument should be an integer”); System.exit(-1); } //end catch 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 Dealing with exceptions
Procedural programming in Java public class Program2 { public static void main(String [] args) { int value1, value2, sum; //declare variables if ( args.length != 2 ) { System.err(“Incorrect number of arguments”); System.exit(-1); } //end if try { //attempt to convert args to integers value1 = Integer.parseInt(args[0]); value2 = Integer.parseInt(args[1]); } //end try catch(NumberFormatException nfe) { System.err(“Arguments must be integers”); System.exit(-1); } //end catch sum = value1 + value2; System.out.println(“Sum is “ + sum); } //end main } //end class Program3 Revised version of addition program. Checks number of arguments Checks that arguments are numbers.
Procedural Programming in Java 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 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 :-
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 import java.io.*; //provides visibility of io facilities public class Greeting { public static void main(String [] args) throws IOException { String line; int age; boolean ok = false; InputStreamReader isr = new InputStreamReader(System.in); BufferedReader in = new BufferedReader(isr); 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 Numeric input Data is input as strings - just as with command-line input. If numeric input is needed, explicit conversion is required with Integer.parseInt() or Double.parseDouble()
Procedural Programming in Java //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 A useful method
Procedural Programming in Java 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 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.
Procedural Programming in Java 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 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.
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 public void methodA(){ //safe code try { //start of try block //any number of statements //that could lead to an exception } //end try block catch(InterruptedException ie){ //code to deal with an IinterruptedException } //end catch catch(IOException ioe){ //code to deal with an IOException }// end catch catch(Exception e){ //code to deal with any Exception }//end catch //further code } //end methodA 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. When an exception occurs, these are scanned in order, to find a matching parameter. If one is found, the exception is cancelled and the handler code executed. All other catch methods are ignored.
Programming in Java - Exception handling 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 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.
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 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 User-defined exceptions
Programming in Java - Exception handling Object Throwable Exception IOException InterruptedException RunTimeException ParseException ArithmeticException NullPointerException IndexOutOfBoundsException ArithmeticException Exception classes fall into two groups - sub-classes of RunTimeException and others. In the case of others :- A method which could give handle the exception rise to an exception either locally. by throwing it or calling a method which might, This does not apply to must declare the fact in a RunTimeExceptions. throws clause, or
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 }//end while return msg; } //end GetMessage public String getMessage() throws IOException { //does not String msg; InputStreamReader isr = new InputStreamReader(System.in); BufferedReader in = new BufferedReader(isr); System.out.println(“Enter message “); msg = in.readLine(); return msg; } //end GetMessage