1 / 58

Program Control, Exceptions, Subroutines

Program Control, Exceptions, Subroutines. Week 4. f or Loop. Initialization and update can have more than one statements. for( i =1,j = 5 ; i < = 5 ; i ++,j--){ System.out.printf (”%3d ", i ); System.out.printf (”%3d ", j); System.out.println (); } // output 1 5 2 4 3 3

nau
Download Presentation

Program Control, Exceptions, Subroutines

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Program Control, Exceptions, Subroutines Week 4

  2. for Loop • Initialization and update can have more than one statements. for(i=1,j=5; i<=5; i++,j--){System.out.printf(”%3d", i); System.out.printf(”%3d", j); System.out.println(); } // output 1 5 2 4 3 3 4 2 5 1

  3. Nested Loops for ( row = 1; row <= 12; row++ ) { for(col=1; col<=12; col++){ // print in 4-character column System.out.printf( "%4d", row * col); } System.out.println(); // Add a carriage return at end of the line. }

  4. enum and for-each Loops for ( ⟨enum-type-name ⟩ ⟨variable-name ⟩ : ⟨enum-type-name ⟩.values() ) { ⟨statements ⟩ } values() is a static member function that returns a list containing all of the values of the enum. Example: enum Day { MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY } ; for ( Day d : Day.values() ) { System.out.print( d ); System.out.print(" is day number "); System.out.println( d.ordinal() ); }

  5. Infinite Loop • Common property: continuation condition is always true. • while(true){ // statements;} • while(1){ // statements;} • while(3){ // statements;} • for(;;){ // statements} • for(inti=0; i<10; ) { // statements do not change the value of i} • And other cases… If your program gets into infinity loop, you have to TERMINATE it by close the running window or Ctrl-C in the command line environment.

  6. break • Unlabeled break • immediately jumps out the innermost loop and continue on to whatever follows that loop in the program. • Labeled break • immediately jumps out the labeled loop and continue on to whatever follows that loop in the program.

  7. Example: unlabeled Output: 1,1 1,2 1,3 2,1 3,1 3,2 3,3 for(inti=1; i<=3; i++){ for(int j=1; j<=3; j++){ System.out.println(i+”,”+j); if(i == 2) break; // if i==2, jump out the inner for loop and continue executing statements C; } // statements C; }

  8. Example: labeled Output: 1,1 1,2 1,3 2,1 out: for(inti=1; i<=3; i++){ for(int j=1; j<=3; j++){ System.out.println(i+”,”+j); if(i == 2) break out; // if i==2, jump out the outer for loop and continue executing statements C; } } // statements C

  9. continue • It skips the current iteration of a loop. • The unlabeled form: • skips to the end of the innermost loop's body and evaluates the boolean expression that controls the loop. • The labeled form: • skips the current iteration of an outer loop marked with the given label.

  10. Example: unlabeled Output: 1,1 1,3 2,1 2,3 3,1 3,3 for(inti=1; i<=3; i++){ for(int j=1; j<=3; j++){ if(j == 2) continue; // if i==2, skip the current iteration of the inner for loop; System.out.println(i+”,”+j); } // statements; }

  11. Example: labeled Output: 1,1 2,1 3,1 label: for(inti=1; i<=3; i++){ for(int j=1; j<=3; j++){ if(j == 2) continue label; // if i==2, skip the current iteration of the inner for loop; System.out.println(i+”,”+j); } } // statements;

  12. switch Statement • The value of the expression can be byte, short, int, char, or enum.

  13. switch Statement • “break;” is optional and makes the computer jump to the end of the switch statement. • If you leave out the break, it will execute the following case statements until meet the next break. • The label “default:”provides a default jump point that is used when the value of the expression is not listed in any case label.

  14. Example • 1. If N = 1, then output would be: • The number is 1. • If N = 3, then output would be: • The number is 3, 6, or 9. • That’s a multiple of 3! • If N = 10, then output would be: • The number is 7 or is outside the range 1 to 9.

  15. enum in switch Statements • Expression can be an enumerated type. • Constants in cases must be values from the enumerated type. enumSeason { SPRING, SUMMER, FALL, WINTER } currentSeason; switch ( currentSeason ) { case WINTER: // ( NOT Season.WINTER ! ) System.out.println("December, January, February"); break; case SPRING: System.out.println("March, April, May"); break; case SUMMER: System.out.println("June, July, August"); break; case FALL: System.out.println("September, October, November"); break; }

  16. Example - Factorial import java.util.Scanner; public class Factorial { public static void main(String args[]) { intn; // input parameter // read in n Scanner sc = new Scanner(System.in); do { n = sc.nextInt(); if (n < 0) { System.out.println("Non-negative number expected!"); } } while (n < 0); // compute n! long factorial = 1; for (inti = 1; i <= n; ++i) { factorial *= i; } System.out.println("n! = " + factorial); } }

  17. Definite Assignment • In Java, it is only legal to use the value of a variable if a value has already been definitely assigned to that variable. • Computer is NOT smarter enough as human being.

  18. Example String computerMove; // computerMove now is a null object; switch ( (int)(3*Math.random()) ) { case 0: computerMove = "Rock"; break; case 1: computerMove = "Scissors"; break; case 2: computerMove = "Paper"; break; } System.out.println("Computer’s move is " + computerMove); // ERROR! Replacing the case label with default can fix this problem; Initialze the string computerMove;

  19. Example String computerMove;int rand;rand = (int)(3*Math.random()); if(rand==0) computerMove= "Rock"; else if(rand==1) computerMove= "Scissors"; else if(rand==2) computerMove= "Paper"; Replacing the else if(rand==2) with only using else can fix this problem; Initializing the string computerMove;

  20. Exceptions in Java

  21. Common Errors/Exceptions • Integer underflow/overflow. • Divided by zero. • File not exists. • Type not matched. • Array index exceeds. • Variable never defined. • Number format exception. • Illegal argument exception. • …

  22. What If Errors Occur? • Terminate the program. • Print out the error message. • Some errors may result in system crash, data lose, or other severe problems. • In this cases, we want to capture errors and program a response different from simply letting the program crash.

  23. Example public void balanceTransfer(Account A, Account B, int amount){ A.credit += amount; // A gets some amount of money; // If some errors happen here; e.g. divided by zero; B.credit -= amount; // won’t be executed; }

  24. try…catch try { ⟨statements-1 ⟩ } catch ( ⟨exception-class-name ⟩ ⟨variable-name ⟩ ) { ⟨statements-2 ⟩ } -------------------- Put all statements which potentially have risk of raising exceptions into the try statements.

  25. Example public void balanceTransfer(Account A, Account B, int amount){ try{ A.credit += amount; // A gets some amount of money; // If some errors happen here; divided by 0; B.credit -= amount; }catch(Exception e){ // catch the exceptions; //if exceptions happen, the try statement will not be //executed. System.out.println(e.getMessage()); } }

  26. Example import java.util.Scanner; enumDay { MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY }; Day weekday; // User’s response as a value of type Day. while ( true ) { String response; // User’s response as a String. System.out.print("Please enter a day of the week: "); Scanner s = new Scanner(System.in); response = s.next(); response = response.toUpperCase(); try { weekday = Day.valueOf(response); break; } catch ( IllegalArgumentException e ){ System.out.println( response + " is not the name of a day of the week." ); } }

  27. Subroutine • Break up a complex task into many small pieces: subroutine. • A subroutine consists of the instructions for carrying out a certain task, grouped together and given a name. • A subroutine can be reused at different places in the program. • A subroutine can be used inside another subroutine.

  28. Black Box • An interface is an interaction between what’s inside the box and what’s outside. • The inside of a black box is called an implementation. Interface Implementation

  29. Black Box • Some rules: • The interface of a black box should be fairly straight-forward, well-defined, and easy to understand. • To use a black box, you shouldn’t need to know any- thing about its implementation; all you need to know is its interface. • The creator of a black box should not need to know anything about the larger systems in which the box will be used.

  30. Static Subroutine • Every subroutine in Java must be defined inside some class. • A subroutine that is a member of a class is often called a method.

  31. Subroutine Definition ⟨modifiers ⟩ ⟨return-type ⟩ ⟨subroutine-name ⟩ ( ⟨parameter-list ⟩ ) { ⟨statements⟩ } <modifiers> : public / private / protected / static / no keywords <return-type> : int / double / String / some class type / void / … <parameter-list> : empty / one or more declarations of the form <type> <parameter-name> • public static void main(String[] args)

  32. Definition Examples publicstatic void playGame(){ // "public" and "static" are modifiers; "void" is the // return-type; "playGame" is the subroutine-name; // the parameter-list is empty. . . . // Statements that define what playGame does go here. }

  33. Definition Examples intgetNextN(int N) { // There are no modifiers; "int" in the return-type; // "getNextN" is the subroutine-name; the parameter-list // includes one parameter whose name is "N" and whose // type is "int". . . . // Statements that define what getNextN does go here. }

  34. Definition Examples staticbooleanlessThan(double x, double y) { // "static" is a modifier; "boolean" is the // return-type; "lessThan" is the subroutine-name; // the parameter-list includes two parameters whose names are // "x" and "y", and the type of each of these parameters // is "double". . . . // Statements that define what lessThan does go here. }

  35. Methods • The subroutine/method doesn’t actually get executed until it is called. • main() is usually called by the system.

  36. Method Call public class MethodCallExample{ public void method1(){ // statements… } public double method2(double x, int y){ // statements… } public String method3(){ double z = method2(3.0, 5); // call method2 // other statements … } }

  37. Public Method public class MethodExample{ public void method1(){ // statements… } public double method2(double x, int y){ // statements… } public String method3(){ double z = method2(3.0, 5); // call method2 // other statements … } } public class MethodCallExample{ MethodExample me = new MethodExample(); public String callMethod(){ double z = me.method2(3.0, 5); // call method2, CORRECT. double z = MethodExample.method2(3.0, 5); // call method2, ERROR!!! Not a static method. // other statements … } }

  38. Private Method public class MethodExample{ public void method1(){ // statements… } private double method2(double x, int y){ // statements… } public String method3(){ double z = method2(3.0, 5); // call method2 // other statements … } } public class MethodCallExample{ MethodExample me = new MethodExample(); public String callMethod(){ double z = me.method2(3.0, 5); // call method2, ERROR!!! // other statements … } } Private method can only be called within the same class

  39. Static Class Method public class MethodExample{ public void method1(){ // statements… } public static double method2(double x, int y){ // statements… } public String method3(){ double z = method2(3.0, 5); // double z = MethodExample.method2(3.0, 5); // call method2 // other statements … } } public class MethodCallExample{ MethodExample me = new MethodExample(); public String callMethod(){ double z = MethodExample.method2(3.0, 5); // call method2, CORRECT. double z = me.method2(3.0, 5); // call method2, not recommended!!! // other statements … } } Always use class name before call it

  40. Variables in Java public class VariableExample{ public int x, y; private String s; public staticintcouter; public int sum(int a, int b){ int addition = a+b; return addition; } } Member Variables Static Member Variables Local Variables

  41. Member Variable • Member variables are called “fields” in Java. • Variables defined outside any methods, but inside a class. • They can be changed by all methods within the class. • Two types: • Non-static member variables. • Static member variables: a static member variable belongs to the class itself, and it exists as long as the class exists.

  42. Local Variable • Local variables: variables defined inside methods. • A local variable in a method exists only while that method is being executed, and is completely inaccessible from outside of that method.

  43. Example public class ClassName{ private intscore; // non-static member variable public static String name; // static member variable public int add(int x, int y){ int sum; // sum is the local variable, only exists in method add sum = x + y; return sum; } public int minus(){ score -= sum; // error: sum is not defined! return score; } }

  44. Static Member Variables • Static member variables are “shared” by all objectsinstantiated from that class. public class SMV{ public static int counter; // other member variables; // other methods } SMV smv1 = new SMV(); smv1.counter++; SMV smv2 = new SMV(); smv2.counter++;

  45. Access Static Member Variables public class ClassFirst { publicstatic memVar_f1; private static memVar_f2; public void method_f1(){ memVar_f1++; // correct memVar_f2++; // correct } } public class ClassSecond{ public ClassFirstfObj = new ClassFirst(); public void method_s1(){ fObj.memVar_f1++; // correct ClassFirst.memVar_f1++; // correct fObj.memVar_f2++; // wrong } }

  46. Named Constants • Sometimes, the value of a variable is not supposed to change after it is initialized. • In Java, the modifier “final” ensures that the value stored in the variable cannot be changed after it has been initialized. • final static double interestRate = 0.05; • It is legal to apply the final modifier to local variables and even to parameters, but it is most useful for member variables.

  47. Named Constants • We often refer to a static member variable that is declared to be final as a named constant, since its value remains constant for the whole time that the program is running. • Usually, give meaningful names to these variables to enhance the program readability. • It is easy to change the value of a named constant.

  48. Enumerated Type Constants • enum Alignment { LEFT, RIGHT, CENTER } • Alignment.LEFT 0 • Alignment.RIGHT  1 • Alignment.CENTER  2 • It is similar to define three named constants • public static final intALIGNMENT_LEFT = 0; • public static final intALIGNMNENT_RIGHT = 1; • public static final intALIGNMENT_CENTER = 2;

  49. Example public class MathExample{ public final static double PI = 3.14; public final static double NATURAL_LOG = 2.72; public final static String AUTHOR = “IDS201”; public double area(double radius){ doubelcircleArea = PI*radius*radius; System.out.println(“The pi is: ”+PI); return circleArea; } public double naturalLog(double x){ double value; value = Math.log(x); System.out.printf(“The log_%f(%f) is %f\n”,NATURAL_LOG, x, value); return value; } public void printMSG(){ System.out.println(“Author is: ”+AUTHOR); } }

  50. Parameters • Provide input to the black box input output

More Related