580 likes | 660 Views
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
E N D
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
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. }
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() ); }
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.
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.
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; }
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
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.
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; }
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;
switch Statement • The value of the expression can be byte, short, int, char, or enum.
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.
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.
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; }
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); } }
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.
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;
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;
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. • …
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.
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; }
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.
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()); } }
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." ); } }
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.
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
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.
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.
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)
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. }
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. }
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. }
Methods • The subroutine/method doesn’t actually get executed until it is called. • main() is usually called by the system.
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 … } }
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 … } }
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
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
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
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.
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.
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; } }
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++;
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 } }
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.
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.
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;
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); } }
Parameters • Provide input to the black box input output