CT 229 Java Syntax Continued 06/10/2006 CT229
Lab Assignments Due Date for current lab assignment : Oct 8 th Before submission make sure that the name of each.java file matches the name given in the assignment sheet!!!! Remember: Electronic Submission @ http://ecrg-vlab01.it.nuigalway.ie/uploader/submissions.html or email: edward.scully@nuigalway.ie subject: CT229 NEW LAB ASSIGNMENT FOR NEXT WEEK!! 06/10/2006 CT229 1
Tutorials Tutorial Problem Sheet available online the week of the tutorial. http://www.nuigalway.ie/staff/ted_scully/ct229/tutorials.html 06/10/2006 CT229 2
Review of Last Week Precedence: Determines the order in which operators act in an expression with more than one operator. Associativity Rule: Specifies the correct order of evaluation when operations are of equal precedence 06/10/2006 CT229 3
Precedence & Associativity Table Prec. Operators Associativity 1 () []. Left to right 2! ~ ++ -- +(unary) -(unary) Right to left ~(unary) (type-cast) 3 * / % Left to right 4 + - Left to right 5 << >> >>> Left to right 6 < <= > >= instanceof Left to right 7 ==!= Left to right 8 & Left to right 9 ^ Left to right 10 Left to right 11 && Left to right 12 Left to right 13?: Right to left 14 = += -= *= /= %= &= ^= = <<= >>= Right to left 06/10/2006 CT229 4
Review of Last Week if statement if Statements if (condition1) action_if_condition1_true; else if (condition2) action_if_condition1_true; else action_if_all_conditions_false; 06/10/2006 CT229 5
Review of Last Week switch Statement int choice; /* user enters 1, 2, 3, or 4 for choice */ switch (choice) case 1: doactionone(); // done if choice == 1 break; // don't do next stmt case 2: doactiontwo(); // if choice == 2 break; case 3: case 4: doactionthreefour(); // if choice == 2,3,4 break; default: displayerror(); // all other cases 06/10/2006 CT229 6
Repetition: while while: Repeat a statement/block while a condition is true Useful when we don't know in advance how many times to repeat (for used more often when we do know) Format while (condition) action; 06/10/2006 CT229 7
Repetition - While int count = 1; while (count < 5) System.out.println("Count is: " + count); count++; Count is: 1 Count is: 2 Count is: 3 Count is: 4 06/10/2006 CT229 8
Repetition - do/while do/while: Like while, but condition tested after action first done Action guaranteed to be executed at least once Useful when action initialises variable used in condition Format: do action; while (condition); 06/10/2006 CT229 9
Repetition do/while int count = 1; do System.out.println("Count is: " + count); count++; while (count < 5); Count is: 1 Count is: 2 Count is: 3 Count is: 4 06/10/2006 CT229 10
do/while example The following program should ask the user for a number that is 1 and 10. If the user enters a number within the range then the user is asked to enter a another number If the user enters a number outside of that range then exit the program 06/10/2006 CT229 11
do/while Example int number; do String numberstr = JOptionPane.showInputDialog("Please enter a number between 1 and 10"); number = Integer.parseInt(numberStr); while ( (number >0) && (number <11) ); JOptionPane.showMessageDialog(null, "Exiting Program"); 06/10/2006 CT229 12
while loop version of example int number; String numberstr = JOptionPane.showInputDialog("Please enter a number between 1 and 10"); number = Integer.parseInt(numberStr); while ((number >0) && (number <11)) numberstr = JOptionPane.showInputDialog("Please enter a number between 1 and 10"); number = Integer.parseInt(numberStr); JOptionPane.showMessageDialog(null, "Exiting Program"); 06/10/2006 CT229 13
Repetition: for Used to repeat block of code specified number of times Useful when number of repetitions known E.g. print 10 lines for (i = 0 ; i < 10 ; i++) System.out.println("Line " + i); 1: Initialise 2: Test 3: Increment Initialise control variable: once, at very start of loop Test: every time, before executing loop body Increment: every time, after loop body, before next test 06/10/2006 CT229 14
For: Notes Initialise Section: Can declare the control variable: for (int x=5; x<10; x++) Scope of variable is until end of loop Test Section: If testing (variable == value) ensure variable does not miss the exact value, particularly with float/double Using >= or <= may be safer Increment Section: Can increment, decrement, add 7, whatever For clarity, use combined assignment operator (x += 7) 06/10/2006 CT229 15
for loop Examples for (int i = 1; i < 10; i+=2) System.out.println( i = " +i); i = 1 i = 3 i = 5 i = 7 i = 9 for (int i = 1; i < 10; i+=3) System.out.println( i = " +i); i = 1 i = 4 i = 7 06/10/2006 CT229 16
for loop Examples for (int i = 1; i < 10; i*=2) System.out.println( i = " +i); i = 1 i = 2 i = 4 i = 8 for (int i = 1; i < 10; i*=3) System.out.println( i = " +i); i = 1 i = 3 i = 9 06/10/2006 CT229 17
for loop Examples for (int i = 10; i > 0; i -=2) System.out.println("i = " +i); i = 10 i = 8 i = 6 i = 4 i = 2 for (int i = 10; i > 0; i-=3) System.out.println("i = " +i); i = 10 i = 7 i = 4 i = 1 06/10/2006 CT229 18
Nested For Loops Placing one for loop inside another Example for (int i = 1; i < 5; i++) for (int j = 1; j < 3; j++) System.out.print((i*j)+" "); System.out.println(); 1 2 2 4 3 6 4 8 06/10/2006 CT229 19
CT 229 Java Methods 06/10/2006 CT229
Methods: Introduction Methods are always members of a class So far, have just had main method in program public class Many pre-defined methods in Java API (e.g. Math methods) Cannot define a method inside another method Definition consists of: Method type Return Type Method Name List of Parameters To call (invoke) method: Write name of method, with list of arguments (data) to pass to method If the method returns a value, a it can be used as part of an expression 06/10/2006 CT229 21
Simple Method import javax.swing.joptionpane; public class WelcomeMethod public static void main(string[] args) welcomemessage(); public static void welcomemessage() JOptionPane.showMessageDialog(null,"Welcome to the program"); 06/10/2006 CT229 22
Defining a Method Format: method-type return-type method-name (parameter-list) declarations and statements: body of method method-type: public/private, static (later topic) return-type: data type of result returned by method, or void if the method does not return a result method-name: any valid identifier (like variable name) parameter-list: next slide 06/10/2006 CT229 23
A Method with Parameters import javax.swing.joptionpane; public class parametermethod public static void main(string[] args) String personsname = "John"; int personsage = 25; printage(personsname, personsage); public static void printage(string name, int age) JOptionPane.showMessageDialog(null, "The age of " + name + " is " + age); 06/10/2006 CT229 24
Parameters Arguments in call printage(personsname, personsage); Map to parameters in method public static void printage(string name, int age) JOptionPane.showMessageDialog(null, "The age of " + name + " is " + age); This mapping is based on position Each argument in call must match corresponding parameter in method definition Arguments and parameters must have matching number, order, type 06/10/2006 CT229 25
Defining a Method Return value: If not void, method must have a statement return expression; If void, method returns at closing "" 06/10/2006 CT229 26
Returning a (String) Value from a Method import javax.swing.joptionpane; public class returningmethod public static void main(string[] args) String name; name = askusername(); JOptionPane.showMessageDialog(null, Username is +name); private static String askusername() String username = JOptionPane.showInputDialog("Please enter your name"); return username; 06/10/2006 CT229 27
Returning a (boolean) Value from a Method // Checks if parameter is an even number public static boolean is_even (int x) int ans = x % 2; if (ans == 0) return true; else return false; 06/10/2006 CT229 28
Returning a (boolean) Value from a Method public static void main(string args[]) boolean result; String numstr = JOptionPane.showInputDialog( Enter a number ); int num = Integer.parseInt(numStr); result = is_even(num); if (result) JOptionPane.showMessageDialog(null, even ); else JOptionPane.showMessageDialog(null, odd ); 06/10/2006 CT229 29
Simple Example (3) function name result = is_even(num); value of the variable in the function s return statement gets copied here argument s value gets copied to corresponding parameter in the function Sample scenario Assume num has the value 17 When is_even is called, 17 gets copied to x ans = (17 % 2) = 1 return statement sends back the value false 06/10/2006 CT229 30
Math Class Methods in Java must be contained in a class Mathematical methods are in class Math, in package java.lang Supports common mathematical calculations java.lang.math example Calculate the square root of 49.0: answer = Math.sqrt(49.0); Method sqrt belongs to class Math Dot (.) allows access to method sqrt The argument 49.0 is located inside parentheses Returns 7.0, which is used in assignment to answer 06/10/2006 CT229 31
Some Math Class Methods Method Description Example abs(x) absolute value of x (this method also has float, int and long versions) abs( 23.7 ) is 23.7 abs( 0.0 ) is 0.0 abs( -23.7 ) is 23.7 ceil(x) rounds x to the smallest integer not less than x ceil( 9.2 ) is 10.0 ceil( -9.8 ) is -9.0 cos(x) trigonometric cosine of x (x is in radians) cos( 0.0 ) is 1.0 exp(x) exponential method ex exp( 1.0 ) is 2.71828 exp( 2.0 ) is 7.38906 floor(x) rounds x to the largest integer not greater than x floor( 9.2 ) is 9.0 floor( -9.8 ) is -10.0 log(x) natural logarithm of x (base e) log( Math.E ) is 1.0 log( Math.E * Math.E ) is 2.0 max( 2.3, 12.7 ) is 12.7 max( -2.3, -12.7 ) is -2.3 min( 2.3, 12.7 ) is 2.3 min( -2.3, -12.7 ) is -12.7 max(x,y) larger value of x and y (this method also has float, int and long versions) min(x,y) smaller value of x and y (this method also has float, int and long versions) pow(x,y) x raised to the power y (xy) pow( 2.0, 7.0 ) is 128.0 pow( 9.0, 0.5 ) is 3.0 sin(x) trigonometric sine of x (x is in radians) sin( 0.0 ) is 0.0 sqrt(x) square root of x sqrt( 900.0 ) is 30.0 sqrt( 9.0 ) is 3.0 tan(x) trigonometric tangent of x (x is in radians) tan( 0.0 ) is 0.0 06/10/2006 CT229 32
Some More Examples From course website: WagesMethod.java: Wages.java re-written with a method to calculate total 06/10/2006 CT229 33
Scope and Methods Data Area When a method is called, space is allocated for storage of its data: Formal Parameters Local Variables This data is lost when the method terminates Local variables cannot be accessed outside method but method can return a value Example demonstrating scoping issues: ScopeExample.java Multiple variables called x with different scopes 06/10/2006 CT229 34