CT 229 Java Syntax Continued

Similar documents
CT 229 Java Syntax Continued

6-1 (Function). (Function) !*+!"#!, Function Description Example. natural logarithm of x (base e) rounds x to smallest integer not less than x


Methods (Deitel chapter 6)

Methods (Deitel chapter 6)

Methods CSC 121 Fall 2014 Howard Rosenthal

Python Lists: Example 1: >>> items=["apple", "orange",100,25.5] >>> items[0] 'apple' >>> 3*items[:2]

Methods CSC 121 Fall 2016 Howard Rosenthal

Lesson #3. Variables, Operators, and Expressions. 3. Variables, Operators and Expressions - Copyright Denis Hamelin - Ryerson University

Chapter 4: Basic C Operators

Methods CSC 121 Spring 2017 Howard Rosenthal

C++ Programming Lecture 11 Functions Part I

Methods: A Deeper Look

CSI31 Lecture 5. Topics: 3.1 Numeric Data Types 3.2 Using the Math Library 3.3 Accumulating Results: Factorial

Variable and Data Type 2

Fundamentals of Programming & Procedural Programming

Introduction to Programming

Chapter 3. Computer Science & Engineering 155E Computer Science I: Systems Engineering Focus. Existing Information.

Intrinsic Functions Outline

Function Example. Function Definition. C Programming. Syntax. A small program(subroutine) that performs a particular task. Modular programming design

C++, How to Program. Spring 2016 CISC1600 Yanjun Li 1

Computer Science & Engineering 150A Problem Solving Using Computers

C Functions. 5.2 Program Modules in C

Fall Semester (081) Dr. El-Sayed El-Alfy Computer Science Department King Fahd University of Petroleum and Minerals

Computer Science & Engineering 150A Problem Solving Using Computers. Chapter 3. Existing Information. Notes. Notes. Notes. Lecture 03 - Functions

Sequence structure. The computer executes java statements one after the other in the order in which they are written. Total = total +grade;

Introduction to Programming

Functions. Systems Programming Concepts

Maths Functions User Manual

Bil 104 Intiroduction To Scientific And Engineering Computing. Lecture 5. Playing with Data Modifiers and Math Functions Getting Controls

Introduction to Engineering gii

MYSQL NUMERIC FUNCTIONS

Operators and Expression. Dr Muhamad Zaini Yunos JKBR, FKMP

CT 229. Java Syntax 26/09/2006 CT229

C++ Overview. Chapter 1. Chapter 2

1001ICT Introduction To Programming Lecture Notes

The Math Class. Using various math class methods. Formatting the values.

The Number object. to set specific number types (like integer, short, In JavaScript all numbers are 64bit floating point

Week 2: Console I/O and Operators Arithmetic Operators. Integer Division. Arithmetic Operators. Gaddis: Chapter 3 (2.14,3.1-6,3.9-10,5.

C Programs: Simple Statements and Expressions

ANSI C Programming Simple Programs

Chapter 6 - Notes User-Defined Functions I

Java Methods. Lecture 8 COP 3252 Summer May 23, 2017

Engineering Problem Solving with C++, Etter/Ingber

BIL 104E Introduction to Scientific and Engineering Computing. Lecture 4

ECET 264 C Programming Language with Applications

Standard Library Functions Outline

Functions and Recursion

Using Free Functions

Introduction to Computer Programming in Python Dr. William C. Bulko. Data Types

Introduction to Computer Science Unit 2. Notes

9 Using Equation Networks

Downloaded from Chapter 2. Functions

Function I/O. Function Input and Output. Input through actual parameters. Output through return value. Input/Output through side effects

Dr M Kasim A Jalil. Faculty of Mechanical Engineering UTM (source: Deitel Associates & Pearson)

CT 229 Fundamentals of Java Syntax

Chapter 3 - Functions

Functions and an Introduction to Recursion Pearson Education, Inc. All rights reserved.

Function I/O. Last Updated 10/30/18

Chapter 2. Outline. Simple C++ Programs

AP CS Unit 3: Control Structures Notes

What did we talk about last time? Examples switch statements

Java Classes: Math, Integer A C S L E C T U R E 8

4. Modules and Functions

Lecture 6: While Loops and the Math Class

Programming: Java. Chapter Objectives. Control Structures. Chapter 4: Control Structures I. Program Design Including Data Structures

PROGRAMMING WITH MATLAB DR. AHMET AKBULUT

CT 229 Methods Continued

Introduction to Computer Science Unit 2. Notes

Product Price Formula extension for Magento2. User Guide

Programming in the Small II: Control

Arithmetic. 2.2.l Basic Arithmetic Operations. 2.2 Arithmetic 37

C++ Programming: From Problem Analysis to Program Design, Fifth Edition. Chapter 6: User-Defined Functions I

Summary of basic C++-commands

Data Types and Basic Calculation

Introduction to Python, Cplex and Gurobi

CIS133J. Working with Numbers in Java

Ordinary Differential Equation Solver Language (ODESL) Reference Manual

Pace University. Fundamental Concepts of CS121 1

Lecture 14. Daily Puzzle. Math in C. Rearrange the letters of eleven plus two to make this mathematical statement true. Eleven plus two =?

All copyrights reserved - KV NAD, Aluva. Dinesh Kumar Ram PGT(CS) KV NAD Aluva

INTRODUCTION TO C++ FUNCTIONS. Dept. of Electronic Engineering, NCHU. Original slides are from

Numerical Data. CS 180 Sunil Prabhakar Department of Computer Science Purdue University

Prasanth Kumar K(Head-Dept of Computers)

Operators Functions Order of Operations Mixed Mode Arithmetic VOID Data. Syntax and type conventions Using the Script window interface

CP122 Computer Science I. Chapter 3: Methods/Functions

Matlab Programming Introduction 1 2

Outline. CSE 1570 Interacting with MATLAB. Starting MATLAB. Outline (Cont d) MATLAB Windows. MATLAB Desktop Window. Instructor: Aijun An

3.1. Chapter 3: The cin Object. Expressions and Interactivity

Introduction to C Language

Using the um-fpu with the Javelin Stamp

Quick MATLAB Syntax Guide

CS110: PROGRAMMING LANGUAGE I

Outline. CSE 1570 Interacting with MATLAB. Starting MATLAB. Outline. MATLAB Windows. MATLAB Desktop Window. Instructor: Aijun An.

How to Design Programs Languages

2 Making Decisions. Store the value 3 in memory location y

Lecture 5: Methods CS2301

C++ PROGRAMMING SKILLS Part 3 User-Defined Functions

Important Java terminology

Introduction to MATLAB

Transcription:

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