Java Script Dr Awad Khalil Computer Science Department

  • Slides: 57
Download presentation
Java. Script Dr. Awad Khalil Computer Science Department AUC Java. Script, by Dr. Khalil

Java. Script Dr. Awad Khalil Computer Science Department AUC Java. Script, by Dr. Khalil 1

Content / Introduction / Basic Concepts / Making Selections – Control Structures / Making

Content / Introduction / Basic Concepts / Making Selections – Control Structures / Making Repetitions (Loops) / Logical Operations / Functions - Methods / Objects Java. Script, by Dr. Khalil 2

Introduction / Java. Script scripting language, is a technology which facilitates a disciplined approach

Introduction / Java. Script scripting language, is a technology which facilitates a disciplined approach to designing computer programs that enhance the functionality and appearance of Web pages. / Java. Script was originally created by Netscape, while Microsoft’s version of Java. Script is called Jscript. Java. Script, by Dr. Khalil 3

Simple Examples – First Program in Java. Script <HTML> <HEAD> <TITLE>A First Program in

Simple Examples – First Program in Java. Script <HTML> <HEAD> <TITLE>A First Program in Java. Script</TITLE> <SCRIPT LANGUAGE=“Java. Script”> document. writeln(“<H 1>Welcome to Java. Script Programming!</H 1>”); </SCRIPT> </HEAD><BODY></BODY> </HTML> Java. Script, by Dr. Khalil 4

Example 2 – Printing on one line <HTML> <HEAD> <TITLE>A First Program in Java.

Example 2 – Printing on one line <HTML> <HEAD> <TITLE>A First Program in Java. Script</TITLE> <SCRIPT> document. write( “<FONT COLOR=‘red’><H 1>Welcome to “ document. writeln(“Java. Script Programming!</H 1></FONT>”); </SCRIPT> </HEAD><BODY></BODY> </HTML> Java. Script, by Dr. Khalil 5

Example 3 – Printing on multiple lines <HTML> <HEAD> <TITLE>Printing Multiple Lines</TITLE> <SCRIPT LANGUAGE=“Java.

Example 3 – Printing on multiple lines <HTML> <HEAD> <TITLE>Printing Multiple Lines</TITLE> <SCRIPT LANGUAGE=“Java. Script”> document. writeln(“<H 1>Welcome to <BR>Java. Script<BR> Programming!</H 1>”); </SCRIPT> </HEAD><BODY></BODY> </HTML> Java. Script, by Dr. Khalil 6

Example 4 – Displaying multiple lines in a dialog box <HTML> <HEAD> <TITLE>Printing Multiple

Example 4 – Displaying multiple lines in a dialog box <HTML> <HEAD> <TITLE>Printing Multiple Lines</TITLE> <SCRIPT LANGUAGE=“Java. Script”> window. alert(“Welcome ton. Java. Scriptn. Programming!”); </SCRIPT> </HEAD><BODY></BODY> </HTML> Java. Script, by Dr. Khalil 7

Example 5 – Adding Integers <HTML> <HEAD> <TITLE>An Addition Program</TITLE> <SCRIPT LANGUAGE=“Java. Script”> var

Example 5 – Adding Integers <HTML> <HEAD> <TITLE>An Addition Program</TITLE> <SCRIPT LANGUAGE=“Java. Script”> var first. Number, // first string entered by user second. Number, // second string entered by user number 1, // first number to add number 2, // second number to add sum; // sum of number 1 and number 2 // read in first number from user as string first. Number = window. prompt( “Enter first integer”, “ 0’ ); // read in second number from user as string second. Number = window. prompt( “Enter second integer”, “ 0’ ); // convert numbers from strings to integers number 1 = parse. Int(first. Number); number 2 = parse. Int(second. Number); // add the numbers sum = number 1 + number 2; // display the results document. writeln( “<H 1>The sum is “ + sum + “</H 1>”); </SCRIPT> </HEAD><BODY></BODY> </HTML> Java. Script, by Dr. Khalil 8

Example 5 – Adding Integers Java. Script, by Dr. Khalil 9

Example 5 – Adding Integers Java. Script, by Dr. Khalil 9

Arithmetic Operators Arithmetic Operation Java. Script Operation Addition + Subtraction - Multiplication * Division

Arithmetic Operators Arithmetic Operation Java. Script Operation Addition + Subtraction - Multiplication * Division / Modulus % Java. Script, by Dr. Khalil 10

Decision Making – Relational Operators Algebraic Relational Operation Java. Script Relation Operation Equal ==

Decision Making – Relational Operators Algebraic Relational Operation Java. Script Relation Operation Equal == Not Equal != Greater than > Greater than or Equal >= Less than < Less than or Equal <= Java. Script, by Dr. Khalil 11

Decision Making – An Example <HTML> <HEAD> <TITLE>Performing Comparisons</TITLE> <SCRIPT LANGUAGE=“Java. Script”> var first,

Decision Making – An Example <HTML> <HEAD> <TITLE>Performing Comparisons</TITLE> <SCRIPT LANGUAGE=“Java. Script”> var first, // first string entered by user second, // second string entered by user // read in first number from user as string first = window. prompt( “Enter first integer: ”, “ 0’ ); // read in second number from user as string second = window. prompt( “Enter second integer: ”, “ 0’ ); document. writeln( “<H 1>Comparison Results</H 1>” ); document. writeln( “<TABLE BORDER = ‘ 1’ WIDTH = ‘ 100%’>” ); if ( first == second ) document. writeln( “<TR><TD>” + first + “ == “ + second + “</TD></TR>” ); if ( first != second ) document. writeln( “<TR><TD>” + first + “ != “ + second + “</TD></TR>” ); if ( first > second ) document. writeln( “<TR><TD>” + first + “ > “ + second + “</TD></TR>” ); if ( first >= second ) document. writeln( “<TR><TD>” + first + “ >= “ + second + “</TD></TR>” ); if ( first < second ) document. writeln( “<TR><TD>” + first + “ < “ + second + “</TD></TR>” ); if ( first <= second ) document. writeln( “<TR><TD>” + first + “ >= “ + second + “</TD></TR>” ); document. writeln( “</TABLE>” ); </SCRIPT> </HEAD><BODY></BODY> </HTML> Java. Script, by Dr. Khalil 12

Java. Script, by Dr. Khalil 13

Java. Script, by Dr. Khalil 13

Java. Script, by Dr. Khalil 14

Java. Script, by Dr. Khalil 14

Key Points / / / The Java. Script language facilitates a disciplined approach to

Key Points / / / The Java. Script language facilitates a disciplined approach to designing computer programs that enhance Web pages. Often Java. Scripts appear in the <HEAD> section of the HTML document. The browser interprets the contents of the <HEAD> section first. The <SCRIPT> tag indicates to the browser that the text that follows is part of a script. Attribute LANGUAGE specifies the scripting language used in the script – such as Java. Script. Every statement should end with a semicolon. Java. Script is case sensitive. A string of characters can be contained between the double quotation (“) marks or single quotation (‘) marks. A string is sometimes called a character string, a message or string literal. The browser’s document object represents the HTML document currently being displayed in the browser. The document object allows a script programmers to specify HTML text to be displayed in the HTML document. The browser contains a complete set of objects that allow script programmers every element of an HTML document. An object resides in the computer’s memory and contains information used by the script. The term object normally implies that attributes (data) and behaviors (methods) are associated with the object. The object’s methods use the attributes to provide useful services to the client of the object – the script that calls the methods. Java. Script, by Dr. Khalil 15

Key Points / / / The document object’s writeln method writes a line of

Key Points / / / The document object’s writeln method writes a line of HTML text in the HTML document. Unlike writeln, document method write does not position the output cursor in the HTML document at the beginning of next line of HTML text after writing its argument. Each write and writeln statement resumes writing characters where the last write or writeln stopped writing characters. Sometimes it is useful to display information in windows called dialog boxes that “pop up” on the screen to grab the user’s attention. Dialog boxes are typically used to display important messages to the user who is browsing the Web page. The browser’s window object displays an alert dialog box with method alert. Method alert requires as its argument the string to display. Normally the characters in a string are displayed exactly as they appear between the double quotes. When a backslash is encountered in a string of characters, the next character is combined with the backslash to form an escape sequence. The escape sequencen is the newline character. It causes the cursor in the HTML document to move to the beginning of the next line in the dialog box. Java. Script, by Dr. Khalil 16

Key Points / / / The keyword var is used to declare the names

Key Points / / / The keyword var is used to declare the names of variables. A variable is a location in the computer’s memory where a value can be stored for use by a program. Though not required, all variables should be declared with a name in a var statement before they are used in a program. A variable name can be any valid identifier. An identifier is a series of characters consisting of letters, digits, underscores (_) and dollar signs ($) that does not contain any spaces. Programmers often indicate the purpose of each variable in the program by placing a Java. Script comment at the end of each line in the declaration. A single-line comment begins with the characters // and terminate at the end of the line. Comments do not cause the browser to perform any action when the script is interpreted; rather, comments are ignored by the Java. Script interpreter. Multiple-line comments begin with delimiter /* and end with delimiter */. All text between the delimiters of the comment is ignored by the Java. Script interpreter. The window object’s prompt method displays a dialog into which the user can type a value. The first argument is a message (called a prompt) that directs the user to take a specific action. The optional second argument is the default string to display in the text field. Java. Script, by Dr. Khalil 17

Key Points / / / / A variable is assigned a value with an

Key Points / / / / A variable is assigned a value with an assignment statement using the assignment operator =. The = operator is called a binary operator because it has two operands. Function parse. Int converts its string argument to an integer. Java. Script has a version of the + operator for string concatenation that enables a string and a value of another data type (including another string) to be concatenated. When a value is placed in a memory location, this value replaces the previous value in that location. Operators in arithmetic expressions are applied in a precise sequence determined by the rules of operator precedence. Parentheses may be used to force the order of evaluation of operators to occur in any sequence desired by the programmer. Java’s if structure allows a program to make a decision based on the truth or falsity of a condition. If the condition is met (the condition is true), the statement in the body of the if structure is executed. If the condition is not met (the condition is false), the body statement is not executed. Conditions in if structures can be formed by using the equality and relational operators. Java. Script, by Dr. Khalil 18

Control Structures if structure if ( student. Grade >= 60 ) document. writeln (

Control Structures if structure if ( student. Grade >= 60 ) document. writeln ( “Passed” ); If/else structure if ( student. Grade >= 60 ) document. writeln ( “Passed” ); else document. writeln ( “Failed” ); -------------------------------------------------if ( student. Grade >= 60 ) document. writeln ( “Passed” ); else { document. writeln ( “Failed<BR>” ); document. writeln ( “You must repeat this course” ); } Java. Script, by Dr. Khalil 19

Control Structures Nested-if structure if ( student. Grade >= 90 ) document. writeln (

Control Structures Nested-if structure if ( student. Grade >= 90 ) document. writeln ( “A” ); else if ( student. Grade >= 80 ) document. writeln ( “B” ); else if ( student. Grade >= 70 ) document. writeln ( “C” ); else if ( student. Grade >= 60 ) document. writeln ( “D” ); else document. writeln ( “F” ); Java. Script, by Dr. Khalil 20

Control Structures switch structure switch ( grade. Letter ) { case “A”: grade. Name

Control Structures switch structure switch ( grade. Letter ) { case “A”: grade. Name = “Excellent; break; case “B”: grade. Name = “Very Good”; break; case “C”: grade. Name = “Good”; break; case “D”: grade. Name = “Sufficient”; break; case “F”: grade. Name = “Fail”; break; default: grade. Name = “Invalid grade”; } Java. Script, by Dr. Khalil 21

Repetition Structures (Loops) while var product = 2; while ( product <= 100 )

Repetition Structures (Loops) while var product = 2; while ( product <= 100 ) product = product * 2; -----------------------------------------------var counter = 1 while ( counter <= 30 ) { sum = sum + score; counter = counter + 1; } -----------------------------------------------Java. Script, by Dr. Khalil 22

Counter-controlled loop – An Example <HTML><HEAD><TITLE>Class Average Program</TITLE> <SCRIPT LANGUAGE="Java. Script"> var total, //

Counter-controlled loop – An Example <HTML><HEAD><TITLE>Class Average Program</TITLE> <SCRIPT LANGUAGE="Java. Script"> var total, // sum of grades grade. Counter, // number of grades entered grade. Value, // grade value average, // average of all grades grade; // grade typed by uesr // initialization phase total = 0; // clear total grade. Counter = 1; // initialize the counter // processing phase while ( grade. Counter <= 10 ) { grade = window. prompt ( "Enter integer grade: ", "0" ); grade. Value = parse. Int( grade ); total = total + grade. Value; grade. Counter = grade. Counter + 1; } average = total / 10; document. writeln( "<H 1>Class average is " + average + "</H 1>" ); </SCRIPT> </HEAD><BODY>Refresh to run the script again</BODY> Java. Script, by Dr. Khalil </HTML> 23

Java. Script, by Dr. Khalil 24

Java. Script, by Dr. Khalil 24

Sentinel-controlled loop <HTML><HEAD><TITLE>Class Average Program</TITLE> <SCRIPT LANGUAGE="Java. Script"> var total, // sum of grades

Sentinel-controlled loop <HTML><HEAD><TITLE>Class Average Program</TITLE> <SCRIPT LANGUAGE="Java. Script"> var total, // sum of grades grade. Counter, // number of grades entered grade. Counter, grade. Value, // grade value grade. Value, average, // average of all grades grade; // grade typed by uesr // initialization phase total = 0; // clear total grade. Counter = 0; // initialize the counter // processing phase // prompt for input and read grade from user grade = window. prompt ( "Enter integer grade, -1 to Quit: ", "0" ); grade. Value = parse. Int( grade ); while ( grade. Value != -1 ) { total = total + grade. Value; grade. Counter = grade. Counter + 1; grade = window. prompt ( "Enter integer grade, -1 to Quit: ", "0" ); grade. Value = parse. Int( grade ); } if ( grade. Counter != 0 ) { average = total / grade. Counter; document. writeln(( "<H 1>Class average is " + average + "</H 1>" ); } else document. writeln(( "<p>No grades were entered!!" ); </SCRIPT> </HEAD><BODY>Refresh to run the script again</BODY> </HTML> Java. Script, by Dr. Khalil 25

Java. Script, by Dr. Khalil 26

Java. Script, by Dr. Khalil 26

Increment and Decrement Operators Assignment Operator Initial variable Value Sample Explanation ASSIGNS expression +=

Increment and Decrement Operators Assignment Operator Initial variable Value Sample Explanation ASSIGNS expression += c=3 c += 7 c=c+7 10 to c -= d=5 d -= 4 d=d– 4 1 to d *= e=4 e *= 5 e=e*5 20 to e /= f=6 f /= 3 f=f/3 2 to f %= g = 12 g %= 0 g=g%9 3 to g Java. Script, by Dr. Khalil 27

Increment and Decrement Operators Operator Called Example Explanation ++ Prefix increment ++a Increment a

Increment and Decrement Operators Operator Called Example Explanation ++ Prefix increment ++a Increment a by 1, then use the new value of a in the expression in which a resides. ++ Postfix increment a++ Use the new value of a in the expression in which a resides, then increment a by 1. -- Prefix decrement --a Decrement a by 1, then use the new value of a in the expression in which a resides. -- Postfix decrement a-- Use the new value of a in the expression in which a resides, then decrement a by 1. Java. Script, by Dr. Khalil 28

Counter-controlled while loop - An Example General Format: initialization; while ( loop. Continuation. Test

Counter-controlled while loop - An Example General Format: initialization; while ( loop. Continuation. Test ) { statement increment; } --------------------------------------------------------<HTML> <HEAD> <TITLE>Counter-controlled loops</TITLE> <SCRIPT LANGUAGE="Java. Script"> var counter = 1; // initialize the counter while ( counter <= 7 ) // loop condition { document. writeln( "<p><FONT SIZE = '" + counter + "'>HTML font size " + counter + "</FONT></p>" ); ++counter; // increment } </SCRIPT> </HEAD><BODY></BODY> Java. Script, by Dr. Khalil </HTML> 29

Java. Script, by Dr. Khalil 30

Java. Script, by Dr. Khalil 30

for loop General Format: for ( initialization; loop. Continuation. Test; increment ) statement -------------------------------------------------------<HTML>

for loop General Format: for ( initialization; loop. Continuation. Test; increment ) statement -------------------------------------------------------<HTML> <HEAD> <TITLE>Counter-controlled loops</TITLE> <SCRIPT LANGUAGE="Java. Script"> // Initialization, loop condition and incrementing // are all included in the for structure header. for ( var counter = 1; counter <= 7; ++counter ) document. writeln( "<p><FONT SIZE = '" + counter + "'>HTML font size " + counter + "</FONT></p>" ); </SCRIPT> </HEAD><BODY></BODY> </HTML> Java. Script, by Dr. Khalil 31

Java. Script, by Dr. Khalil 32

Java. Script, by Dr. Khalil 32

Calculating Compound Interest with for loop <HTML><HEAD><TITLE>Calculating Compound Interest</TITLE> <SCRIPT LANGUAGE="Java. Script"> var amount,

Calculating Compound Interest with for loop <HTML><HEAD><TITLE>Calculating Compound Interest</TITLE> <SCRIPT LANGUAGE="Java. Script"> var amount, principal = 1000, rate = 0. 1; document. writeln( "<TABLE BORDER='100' WIDTH='100%'>" ); document. writeln( "<TR><TD WIDTH= '100'><B>Year</B></TD>" ); document. writeln( "<TD><B>Amount on deposit</B></TD></TR>" ); for ( var year = 1; year <= 10; ++year ) { amount = principal * Math. pow(1. 0 + rate, year); document. writeln( "<TR><TD>" + year + "</TD><TD>" + Math. round(amount * 100) / 100 + "<TD></TR>" ); } doccument. writeln( "</TABLE>" ); </SCRIPT> </HEAD><BODY></BODY> </HTML> Java. Script, by Dr. Khalil 33

Java. Script, by Dr. Khalil 34

Java. Script, by Dr. Khalil 34

The do/while loop General Format: do { statement } while ( condition ); --------------------------------------------------<HTML>

The do/while loop General Format: do { statement } while ( condition ); --------------------------------------------------<HTML> <HEAD> <TITLE>Using the do/while loop</TITLE> <SCRIPT LANGUAGE="Java. Script"> var counter = 1; do { document. writeln( "<H" + counter + ">This is an H" + counter + " level head" + "</H" + counter + ">" ); ++ counter; } while ( counter <= 6 ); </SCRIPT> </HEAD><BODY></BODY> </HTML> Java. Script, by Dr. Khalil 35

Java. Script, by Dr. Khalil 36

Java. Script, by Dr. Khalil 36

The Logical Operators Logical Operation Java. Script Operat. OR Negation (Not) ! OR ll

The Logical Operators Logical Operation Java. Script Operat. OR Negation (Not) ! OR ll AND && Java. Script, by Dr. Khalil Example ! ( grade == sentinel. Value) (gender == 1) l l (age >= 65) (gender == 1) && (age >= 65) 37

Demonstrating the Logical Operators <HTML><HEAD><TITLE>Demonstrating the logical operators</TITLE> <SCRIPT LANGUAGE="Java. Script"> document. writeln( "<TABLE

Demonstrating the Logical Operators <HTML><HEAD><TITLE>Demonstrating the logical operators</TITLE> <SCRIPT LANGUAGE="Java. Script"> document. writeln( "<TABLE BORDER='10' WIDTH='100%'>" ); document. writeln( "<TR><TD WIDTH= '25%'>Logical AND (&&)</TD>" + "<TD>false && false: " + ( false && false ) + "<BR>false && true: " + ( false && true ) + "<BR>true && false: " + ( true && false ) + "<BR>true && true: " + ( true && true ) + "</TD>" ); document. writeln( "<TR><TD WIDTH= '25%'>Logical OR (||)</TD>" + "<TD>false || false: " + ( false || false ) + "<BR>false || true: " + ( false || true ) + "<BR>true || false: " + ( true || false ) + "<BR>true || true: " + ( true || true ) + "</TD>" ); document. writeln( "<TR><TD WIDTH= '25%'>Logical NOT (!)</TD>" + "<TD>!false: " + ( !false ) + "<BR>!true: " + ( !true ) + "</TD>" ); doccument. writeln( "</TABLE>" ); </SCRIPT> </HEAD><BODY></BODY> </HTML> Java. Script, by Dr. Khalil 38

Java. Script, by Dr. Khalil 39

Java. Script, by Dr. Khalil 39

Functions / / / / / Experience has shown that the best way to

Functions / / / / / Experience has shown that the best way to develop and maintain a large program is to construct it from small, simple pieces or modules. This technique is called divide and conquer. Modules in Java. Script are called functions. Java. Script programs are written by combining new functions that the programmer writes with “prepackaged” functions and objects available in Java. Script. The “prepackaged” functions that belong to Java. Script objects are often called methods. The term method implies that the function belongs to a particular object. The programmer can write programmer-defined functions to define specific tasks that may be used at many points in a script. The actual statements defining the function are written only once, and these statements are hidden from other functions. A function is invoked by a function call. The function call specifies the function name and provides information (as arguments) that the called function needs to do its task. Functions allow the programmer to modularize a program. All variables declared in function definitions are local variables – they are known only in the function in which they are defined. Most functions have parameters that provide the means for communicating information between functions via function calls. A function’s parameters are also considered to be local variables. The divide-conquer approach to program development makes program development more manageable. Java. Script, by Dr. Khalil 40

Functions / / / The () represent the function call operator The return statement

Functions / / / The () represent the function call operator The return statement passes the result of a function call back to the calling function. The format of a function definition is Function function-name( parameter-list ) { declarations and statements } Java. Script, by Dr. Khalil 41

Functions – Programmer-defined Functions <HTML><HEAD><TITLE>A Programmer-Defined Square Function</TITLE> <SCRIPT LANGUAGE="Java. Script"> document. writeln( "<H

Functions – Programmer-defined Functions <HTML><HEAD><TITLE>A Programmer-Defined Square Function</TITLE> <SCRIPT LANGUAGE="Java. Script"> document. writeln( "<H 1>Square the numbers from 1 to 10</H 1>" ); // square the numbers from 1 to 10 for ( var x = 1; x <= 10; ++x ) document. writeln( "The square of " + x + " is " + square( x ) + "<BR>" ); // square function definition function square( y ) { return y * y; } </SCRIPT> </HEAD><BODY></BODY> </HTML> Java. Script, by Dr. Khalil 42

Java. Script, by Dr. Khalil 43

Java. Script, by Dr. Khalil 43

Methods / / / The Math object’s max method determines the larger of its

Methods / / / The Math object’s max method determines the larger of its two statement values. The Math object’s random method generates a real value from 0. 0 up to (but not including) 1. 0. Math object’s floor rounds its real number argument to the closest integer not greater than its argument’s value. The values produced directly by random are always in the range: 0. 0 <= Math. random() < 1. 0 We can generalize picking a random number from a range of values by writing: value = Math. floor( a + Math. random() * b) ; Where a is the shifting value (the first number in the desired range of consecutive integers) and b is the scaling factor (the width of the desired range of consecutive integers). Java. Script, by Dr. Khalil 44

<HTML><HEAD><TITLE>A Programmer-Defined maximum Function</TITLE> <SCRIPT LANGUAGE="Java. Script"> var input 1 = window. prompt( "Enter

<HTML><HEAD><TITLE>A Programmer-Defined maximum Function</TITLE> <SCRIPT LANGUAGE="Java. Script"> var input 1 = window. prompt( "Enter first number", "0" ); var input 2 = window. prompt( "Enter second number", "0" ); var input 3 = window. prompt( "Enter third number", "0" ); var value 1 = parse. Int( input 1 ); var value 2 = parse. Int( input 2 ); var value 3 = parse. Int( input 3 ); var max. Value = maximum( value 1, value 2, value 3 ); document. writeln( "First number: " + value 1 + "<BR>Second number: " + value 2 + "<BR>Third number: " + value 3 + "<BR> Maximum is: " + max. Value ); // maximum function definition function maximum( x, y, z ) { return Math. max( x, Math. max( y, z ) ); } </SCRIPT> </HEAD><BODY></BODY> </HTML> Java. Script, by Dr. Khalil 45

Random Number Generation <HTML><HEAD><TITLE>Shifted and Scaled Random Integers</TITLE> <SCRIPT LANGUAGE="Java. Script"> var value; document.

Random Number Generation <HTML><HEAD><TITLE>Shifted and Scaled Random Integers</TITLE> <SCRIPT LANGUAGE="Java. Script"> var value; document. writeln( "<H 1>Random Numbers</H 1>" + "<TABLE BORDER = '5' WIDTH = '50%'><TR>" ); for ( var i = 1; i <= 20; i++ ) { value = Math. floor( 1 + Math. random() * 6 ); document. writeln( "<TD>" + value + "</TD>" ); if ( i % 5 == 0 && i != 20 ) document. writeln( "</TR><TR>" ); } document. writeln( "</TR></TABLE>" ); </SCRIPT> </HEAD><BODY></HTML> Java. Script, by Dr. Khalil 46

Java. Script, by Dr. Khalil 47

Java. Script, by Dr. Khalil 47

Key Points / / / / Any computing problem can be solved by executing

Key Points / / / / Any computing problem can be solved by executing a series of actions in specific order. A procedure for solving a problem in terms of the actions to be executed and the order in which these actions are to be executed is called an algorithm. Specifying the order in which statements are to be executed in a computer program is called program control. Normally, statements in a program are executed one after the other, in the order they are written. This is called sequential execution. Various Java. Script statements enable the programmer to specify that the next statement to be executed may be other than the next one in sequence. This is called transfer of control. All programs can be written in terms of only three control structures, namely by the sequence structure, the selection structure and the repetition structure. Java. Script provides three types of selection structures. The if selection structure either performs (selects) an action if a condition is true or skips the action if the condition is false. The if/else selection structure performs an action if a condition is true and performs a different action if the condition is false. The switch selection structure performs one of many different actions, depending on the value of an expression. Java. Script provides four types of repetition structures, namely while, do/while, for, and for/in. Java. Script, by Dr. Khalil 48

Arrays / / / / / Arrays are data structures consisting of related data

Arrays / / / / / Arrays are data structures consisting of related data items. An array is a group of memory locations that all have the same name and are normally of the same type. To refer to a particular location or element in the array, specify the name of the array and the position number (index ) of the particular element in the array. ( The index (or subscript) must be an integer or an integer expression and the first element in every array is of index 0. The length (size) of an array is the number of its elements and is determined by array. Name. length. An array in Java. Script is an Array object. Operator new is used to dynamically allocate the number of elements required by an array. Operator new creates an object as the program executes, by obtaining enough memory to store an object of the type specified to the right of new. The process of creating new objects is also known as creating an instance or instantiating an object. An array can be initialized with a comma-separated initializerl ist enclosed in square brackets [ ]. Java. Script’s for/in control structure enables a script to perform a task for each element in an array: for ( var element in array. Name )Java. Script, by Dr. Khalil 49 statement

Arrays – An Example I <HTML><HEAD><TITLE>Initializing an Array</TITLE> <SCRIPT LANGUAGE="Java. Script"> // this function

Arrays – An Example I <HTML><HEAD><TITLE>Initializing an Array</TITLE> <SCRIPT LANGUAGE="Java. Script"> // this function is called when the <BODY> element's // ONLOAD event occurs. function initialize. Arrays() { var n 1 = new Array( 5 ); // allocate 5 -element Array var n 2 = new Array(); // allocate empty Array // assign values to each element of Array n 1 for ( var i = 0; i < n 1. length; ++i ) n 1[i] = i * i; // create and initialize 6 elements in Array n 2 for ( i = 0; i < 6; ++i ) n 2[i] = 2 * i; output. Array( ( "Array n 1 contains", n 1 ); output. Array( "Array n 2 contains", n 2 ); } // output "header" followed by a two-column table // containing subscripts and elements of " the. Array" function output. Array( header, the. Array ) { document. writeln(( "<H 2>" + header + "</H 2>" ); document. writeln(( "<TABLE BORDER='10' WIDTH='100%'>" ); document. writeln(( "<TR><TD WIDTH='100'><B>Subscript</B>“ + "<TD><B>Value</B></TR>" ); for ( var i = 0; i < the. Array. length; i++ ) document. writeln(( "<TR><TD>" + i + "<TD>" + the. Array[i] + "</TR>" ); document. writeln(( "</TABLE>" ); } </SCRIPT> </HEAD> <BODY ONLOAD = "initialize. Arrays ()"> "initialize. Arrays()"> </BODY> Java. Script, by Dr. Khalil </HTML> 50

Java. Script, by Dr. Khalil 51

Java. Script, by Dr. Khalil 51

Arrays – An Example II <HTML><HEAD><TITLE>Student Poll Program</TITLE> <SCRIPT LANGUAGE="Java. Script"> function start() {

Arrays – An Example II <HTML><HEAD><TITLE>Student Poll Program</TITLE> <SCRIPT LANGUAGE="Java. Script"> function start() { var responses = [ 1, 2, 6, 4, 8, 5, 9, 7, 8, 10, 1, 6, 3, 8, 6, 10, 3, 8, 2, 7, 6, 5, 7, 6, 8, 6, 7, 5, 6, 6, 5, 6, 7, 5, 6, 4, 8, 6, 8, 10 ]; var frequency = [ , 0, 0, 0 ]; for ( var answer in responses ) ++frequency[ responses[ answer ] ]; document. writeln( "<TABLE BORDER='10' WIDTH='100%'>" ); document. writeln( "<TR><TD WIDTH='100'><B>Rating</B>" + "<TD><B>Frequency</B></TR>" ); for ( var rating = 1; rating < frequency. length; ++rating ) document. writeln( "<TR><TD>" + rating + "<TD>" + frequency[rating] + "<TR>" ); document. writeln( "</TABLE>" ); } </SCRIPT> </HEAD> <BODY ONLOAD = "start()"> </BODY></HTML> Java. Script, by Dr. Khalil 52

Java. Script, by Dr. Khalil 53

Java. Script, by Dr. Khalil 53

Objects / / / / Objects are a natural way of thinking about the

Objects / / / / Objects are a natural way of thinking about the world. Objects encapsulate data (attributes) and methods (behavior). Objects have the property of information hiding. Programs communicate with objects by using well-defined interfaces. World Wide Web browsers have a set of objects that encapsulate the elements of an HTML document and expose to a Java. Script programmer attributes and behaviors that enable a Java. Script program to interact with (or script) the elements (i. e. , objects) in an HTML document. Math object methods allow programmers to perform many common mathematical calculations. An object’s methods are called by writing the name of the object followed by a dot (. ) and the name of the method. In parentheses following the method name is the argument (or a commaseparated list of arguments) to the method. Java. Script, by Dr. Khalil 54 String object provides several methods enabling processing String

Math Object’s Method Description abs( x ) Absolute value of x round( x )

Math Object’s Method Description abs( x ) Absolute value of x round( x ) Rounds x to the closest integer ceil( x ) Rounds x to the smallest integer not less than x sin( x ) Trigonometric sine of x (x in radians) cos( x ) Trigonometric cosine of x (x in radians) sqrt( x ) Square root of x exp( x ) Exponential method ex tan( x ) Trigonometric tangent of x (x in radians) floor( x ) Rounds x to the largest integer not greater than x log( x ) Natural logarithm of x (base e) max( x, y ) Larger value of x and y min( x, y ) Smaller value of x and y pow( x, y ) X raised to power y (xy) Java. Script, by Dr. Khalil 55

String Object’s Methods Java. Script, by Dr. Khalil 56

String Object’s Methods Java. Script, by Dr. Khalil 56

Thank you Java. Script, by Dr. Khalil 57

Thank you Java. Script, by Dr. Khalil 57