59
Chapter 2 Simple Programs

Chapter 2 Simple Programs. © Judith Bishop 2001 2 Contents 2.1 Three starter programs 2.2 The structure of a program 2.3 Basics of object orientation

Embed Size (px)

Citation preview

Page 1: Chapter 2 Simple Programs. © Judith Bishop 2001 2 Contents 2.1 Three starter programs 2.2 The structure of a program 2.3 Basics of object orientation

Chapter 2Simple Programs

Page 2: Chapter 2 Simple Programs. © Judith Bishop 2001 2 Contents 2.1 Three starter programs 2.2 The structure of a program 2.3 Basics of object orientation

© Judith Bishop 20012

Contents

2.1 Three starter programs

2.2 The structure of a program

2.3 Basics of object orientation

2.4 Beginning with output

2.5 Simple calculations

Page 3: Chapter 2 Simple Programs. © Judith Bishop 2001 2 Contents 2.1 Three starter programs 2.2 The structure of a program 2.3 Basics of object orientation

© Judith Bishop 20013

2.1 Three Sample Programs

Page 4: Chapter 2 Simple Programs. © Judith Bishop 2001 2 Contents 2.1 Three starter programs 2.2 The structure of a program 2.3 Basics of object orientation

© Judith Bishop 20014

Example 2.1 Welcome

class Welcome {

/* Welcome program by J M Bishop Dec 1996 * --------------- Java 2 April 2000 * Illustrates a simple program displaying a message. */

Welcome ( ) { System.out.println("Welcome to Java Gently!"); }

public static void main (String [ ] args) { new Welcome( ); }}

Welcome to Java Gently!

Page 5: Chapter 2 Simple Programs. © Judith Bishop 2001 2 Contents 2.1 Three starter programs 2.2 The structure of a program 2.3 Basics of object orientation

© Judith Bishop 20015

Basic outline of a program with comments

class Welcome {

/* Welcome program by J M Bishop Dec 1996 * --------------- Java 2 April 2000 * Illustrates a simple program displaying a message. */

public static void main (String [ ] args) {

}}

Page 6: Chapter 2 Simple Programs. © Judith Bishop 2001 2 Contents 2.1 Three starter programs 2.2 The structure of a program 2.3 Basics of object orientation

© Judith Bishop 20016

Constructing the program object

class Welcome {

/* Welcome program by J M Bishop Dec 1996 * --------------- Java 2 April 2000 * Illustrates a simple program displaying a message. */

Welcome ( ) {

}

public static void main (String [ ] args) { new Welcome( ); }}

Page 7: Chapter 2 Simple Programs. © Judith Bishop 2001 2 Contents 2.1 Three starter programs 2.2 The structure of a program 2.3 Basics of object orientation

© Judith Bishop 20017

Executing a statement

class Welcome {

/* Welcome program by J M Bishop Dec 1996 * --------------- Java 2 April 2000 * Illustrates a simple program displaying a message. */

Welcome ( ) { System.out.println("Welcome to Java Gently!"); }

public static void main (String [ ] args) { new Welcome( ); }}

Welcome to Java Gently!

Page 8: Chapter 2 Simple Programs. © Judith Bishop 2001 2 Contents 2.1 Three starter programs 2.2 The structure of a program 2.3 Basics of object orientation

© Judith Bishop 20018

Example 2 Drawing a flag

import Java.awt.*;import java.awt.event.*;

class FlagMaker1 extends Frame { FlagMaker1 ( ) { add ("Center", new Flag( )); setTitle ("A Flag"); setSize (300, 200); setVisible (true); }

public static void main (String [ ] args) {

new FlagMaker1 ( ); }}

class Flag extends Canvas { public void paint (Graphics g)

{ // Draw the flag using

coloured rectangles g.setColor (Color.black); g.fillRect (40,40,200,40); g.setColor (Color.red); g.fillRect (40,80,200,40); g.setColor (Color.yellow); g.fillRect (40,120,200,40);

// Label the drawing g.setColor (Color.black);

g.drawString("Germany",100,180);

}}

•When setVisible is executed, paint is called and the flag is drawn.

Page 9: Chapter 2 Simple Programs. © Judith Bishop 2001 2 Contents 2.1 Three starter programs 2.2 The structure of a program 2.3 Basics of object orientation

© Judith Bishop 20019

Output from FlagMaker1

Page 10: Chapter 2 Simple Programs. © Judith Bishop 2001 2 Contents 2.1 Three starter programs 2.2 The structure of a program 2.3 Basics of object orientation

© Judith Bishop 200110

Example 2.3 The Curio Store

class CurioStore1 { Curio mugs, tshirts, carvings; CurioStore1 ( ) { mugs = new Curio( "Traditional mugs", 6, "beaded in Ndebele style"); tshirts = new Curio("T-shirts", 30, "sizes M to XL"); carvings = new Curio("Masks", 80, "carved in wood"); System.out.println("The Polelo Curio Store sells\n"); mugs.write( ); tshirts.write( ); carvings.write( ); } public static void main (String [ ] args) { new CurioStore1 ( ); }}

Declare three objects

Createthree objects

Writethree objects

Page 11: Chapter 2 Simple Programs. © Judith Bishop 2001 2 Contents 2.1 Three starter programs 2.2 The structure of a program 2.3 Basics of object orientation

© Judith Bishop 200111

The Curio class

class Curio { String name; int price; String description; Curio (String n, int p, String d) { name = n; price = p; description = d; } void write ( ) { System.out.println(name + " " + description + " for G" + price); }}

Detailsof a curio

Writinga curio

Page 12: Chapter 2 Simple Programs. © Judith Bishop 2001 2 Contents 2.1 Three starter programs 2.2 The structure of a program 2.3 Basics of object orientation

© Judith Bishop 200112

Output from the program

The Polelo Curio Store sells

Traditional mugs beaded in Ndebele style for G6

T-shirts sizes M to XL for G30

Masks carved in wood for G80

Page 13: Chapter 2 Simple Programs. © Judith Bishop 2001 2 Contents 2.1 Three starter programs 2.2 The structure of a program 2.3 Basics of object orientation

© Judith Bishop 200113

2.1 The structure of a program

Page 14: Chapter 2 Simple Programs. © Judith Bishop 2001 2 Contents 2.1 Three starter programs 2.2 The structure of a program 2.3 Basics of object orientation

© Judith Bishop 200114

Structure of a program

A program describes a set of one or more Java classes that can be compiled and run.

class Welcome {

/* Welcome program by J M Bishop Dec 1996 * --------------- Java 2 April 2000 * Illustrates a simple program displaying a message. */

Welcome ( ) { System.out.println("Welcome to Java Gently!"); }

public static void main (String [ ] args) { new Welcome( ); }}

Page 15: Chapter 2 Simple Programs. © Judith Bishop 2001 2 Contents 2.1 Three starter programs 2.2 The structure of a program 2.3 Basics of object orientation

© Judith Bishop 200115

Structure of a program - a class

A class describes the variables and methods appropriate to some real-world entity. Welcome is a class, so is Curio.

class Curio { String name; int price; String description; Curio (String n, int p, String d) { name = n; price = p; description = d; } void write ( ) { System.out.println(name + " " + description + " for G" + price); }}

Page 16: Chapter 2 Simple Programs. © Judith Bishop 2001 2 Contents 2.1 Three starter programs 2.2 The structure of a program 2.3 Basics of object orientation

© Judith Bishop 200116

Structure of a program - identifiers

An identifier is the name of an entity in Java

class Welcome {

/* Welcome program by J M Bishop Dec 1996 * --------------- Java 2 April 2000 * Illustrates a simple program displaying a message. */

Welcome ( ) { System.out.println("Welcome to Java Gently!"); }

public static void main (String [ ] args) { new Welcome( ); }}

Page 17: Chapter 2 Simple Programs. © Judith Bishop 2001 2 Contents 2.1 Three starter programs 2.2 The structure of a program 2.3 Basics of object orientation

© Judith Bishop 200117

Structure of a program - keywords

A keyword has a special meaning in Java and cannot be used as an identifier.

class Welcome {

/* Welcome program by J M Bishop Dec 1996 * --------------- Java 2 April 2000 * Illustrates a simple program displaying a message. */

Welcome ( ) { System.out.println("Welcome to Java Gently!"); }

public static void main (String [ ] args) { new Welcome( ); }}

Page 18: Chapter 2 Simple Programs. © Judith Bishop 2001 2 Contents 2.1 Three starter programs 2.2 The structure of a program 2.3 Basics of object orientation

© Judith Bishop 200118

Structure of a program - comments

A comment explains a part of a program but causes no action.

class Welcome {

/* Welcome program by J M Bishop Dec 1996 * --------------- Java 2 April 2000 * Illustrates a simple program displaying a message. */

Welcome ( ) { System.out.println("Welcome to Java Gently!"); }

public static void main (String [ ] args) { new Welcome( ); }}

Page 19: Chapter 2 Simple Programs. © Judith Bishop 2001 2 Contents 2.1 Three starter programs 2.2 The structure of a program 2.3 Basics of object orientation

© Judith Bishop 200119

Structure of a program - statements

A statement causes an action.

class Welcome {

/* Welcome program by J M Bishop Dec 1996 * --------------- Java 2 April 2000 * Illustrates a simple program displaying a message. */

Welcome ( ) { System.out.println("Welcome to Java Gently!"); }

public static void main (String [ ] args) { new Welcome( ); }}

Page 20: Chapter 2 Simple Programs. © Judith Bishop 2001 2 Contents 2.1 Three starter programs 2.2 The structure of a program 2.3 Basics of object orientation

© Judith Bishop 200120

Structure of a program - constructors

A constructor is activated when an object of that class is instantiated.

class Welcome {

/* Welcome program by J M Bishop Dec 1996 * --------------- Java 2 April 2000 * Illustrates a simple program displaying a message. */

Welcome ( ) { System.out.println("Welcome to Java Gently!"); }

public static void main (String [ ] args) { new Welcome( ); }}

Page 21: Chapter 2 Simple Programs. © Judith Bishop 2001 2 Contents 2.1 Three starter programs 2.2 The structure of a program 2.3 Basics of object orientation

© Judith Bishop 200121

Structure of a program - methods

A method groups together statements to provide structured functionality. Constructors are also methods.

class Welcome {

/* Welcome program by J M Bishop Dec 1996 * --------------- Java 2 April 2000 * Illustrates a simple program displaying a message. */

Welcome ( ) { System.out.println("Welcome to Java Gently!"); }

public static void main (String [ ] args) { new Welcome( ); }}

Page 22: Chapter 2 Simple Programs. © Judith Bishop 2001 2 Contents 2.1 Three starter programs 2.2 The structure of a program 2.3 Basics of object orientation

© Judith Bishop 200122

Structure of a program - parameters

Parameters supply variations to a method.

class CurioStore1 { Curio tshirts, carvings; CurioStore1 ( ) { tshirts = new Curio("T-shirts", 30, "sizes M to XL"); carvings = new Curio("Masks", 80, "carved in wood"); System.out.println("The Polelo Curio Store sells\n"); tshirts.write( ); carvings.write( ); } public static void main (String [ ] args) { new CurioStore1 ( ); }}

Page 23: Chapter 2 Simple Programs. © Judith Bishop 2001 2 Contents 2.1 Three starter programs 2.2 The structure of a program 2.3 Basics of object orientation

© Judith Bishop 200123

Structure of a program - objects

Objects are instantiated from classes by means of the new statement.

class CurioStore1 { Curio tshirts, carvings; CurioStore1 ( ) { tshirts = new Curio("T-shirts", 30, "sizes M to XL"); carvings = new Curio("Masks", 80, "carved in wood"); System.out.println("The Polelo Curio Store sells\n"); tshirts.write( ); carvings.write( ); } public static void main (String [ ] args) { new CurioStore1 ( ); }}

Page 24: Chapter 2 Simple Programs. © Judith Bishop 2001 2 Contents 2.1 Three starter programs 2.2 The structure of a program 2.3 Basics of object orientation

© Judith Bishop 200124

Structure of a program - variables

A variable contains a value, either simple or an entire object

class Curio { String name; int price; String description; Curio (String n, int p, String d) { name = n; price = p; description = d; } void write ( ) { System.out.println(name + " " + description + " for G" + price); }}

Declaringvariables

Usingvariable

s

Page 25: Chapter 2 Simple Programs. © Judith Bishop 2001 2 Contents 2.1 Three starter programs 2.2 The structure of a program 2.3 Basics of object orientation

© Judith Bishop 200125

More on identifiers

Identifiers have certain rules: no spaces case sensitive letters, digits and underscores

allowed

Valid identifiers description noOfPages year2001

Invalid identifiers descr. no of pages 2001

Identifier conventions classes start with capitals everything else starts with a

small inner words start with a capital

for readability

Some identifiers from earlier programs Welcome System out println main String args masks mugs CurioStore1 Curio n p

price setColor

drawString

Page 26: Chapter 2 Simple Programs. © Judith Bishop 2001 2 Contents 2.1 Three starter programs 2.2 The structure of a program 2.3 Basics of object orientation

© Judith Bishop 200126

2.3 Basics of Object Orientation

Page 27: Chapter 2 Simple Programs. © Judith Bishop 2001 2 Contents 2.1 Three starter programs 2.2 The structure of a program 2.3 Basics of object orientation

© Judith Bishop 200127

Model diagrams

Object-oriented programs can be described in UML

Unified Modelling Language

Global industry standard applicable to programs and systems at most levels

Some additions made in Java Gently for small programs

Page 28: Chapter 2 Simple Programs. © Judith Bishop 2001 2 Contents 2.1 Three starter programs 2.2 The structure of a program 2.3 Basics of object orientation

© Judith Bishop 200128

Classes

A Java program consists of a set of one or more inter-dependent classes

Classes describe the properties and capabilities of the objects in real life with which the program deals

Notation: Classes have dashed lines and space for a name, variables and methods.

NOTATION EXAMPLES

Classid

variables

methods

Classid Curio

namepricedescription

Curio()write()

Curio

Page 29: Chapter 2 Simple Programs. © Judith Bishop 2001 2 Contents 2.1 Three starter programs 2.2 The structure of a program 2.3 Basics of object orientation

© Judith Bishop 200129

Objects

An object is a concrete realization of a class definition. Notation: Objects have solid lines and the name is

underlined.

objectid

variables

methods

objectid

mugs

name

price

description

Curio()

write()

mugs

NOTATIONS

EXAMPLES

Page 30: Chapter 2 Simple Programs. © Judith Bishop 2001 2 Contents 2.1 Three starter programs 2.2 The structure of a program 2.3 Basics of object orientation

© Judith Bishop 200130

mugs

name = “Traditional mugs”price = 6description = “beaded in Ndebele style”

Curio()write()

:CurioStore1

mugstshirtscarvings

CurioStore1()

Variables

A variable constitutes storage in the computer which can hold values that change.

Notation: simple variables indicate values with an equals sign object variables refer to the object itself with an arrow.

Page 31: Chapter 2 Simple Programs. © Judith Bishop 2001 2 Contents 2.1 Three starter programs 2.2 The structure of a program 2.3 Basics of object orientation

© Judith Bishop 200131

Declaring and instantiating object variables

Declaration of an object variableClassid objectid;

Classid objectid1, objectid2, ... objectidn;

An object variable with the identifier objectid is declared and given a value null.

There may not be duplicate object variable identifiers in a class.

Instantiation of an object objectid = new Classid (parameterlist);

A new object is created for the object variable referred to by objectid according to the specifications of the class Classid.

The constructor of Classid is called with the parameterlist given (if any).

syntax

semantics

Page 32: Chapter 2 Simple Programs. © Judith Bishop 2001 2 Contents 2.1 Three starter programs 2.2 The structure of a program 2.3 Basics of object orientation

© Judith Bishop 200132

Model of object instantiation

A snapshot of the situation after the mugs and tshirts have been instantiated as objects and just before the carvings object is handled.

tshirts

name = T-shirtsprice = 30description = sizes M to XL

Curio()write()

mugs

name = Traditional mugsprice = 6description = beaded in Ndebele style

Curio()write()

:CurioStore1

mugstshirtscarvings = null

CurioStore1()

Page 33: Chapter 2 Simple Programs. © Judith Bishop 2001 2 Contents 2.1 Three starter programs 2.2 The structure of a program 2.3 Basics of object orientation

© Judith Bishop 200133

Indicating the class

object reference

object instantiatio

n

objects shown

collapsed

:CurioStore1

mugstshirtscarvings = null

CurioStore1()

mugs

tshirts

CurioCurioStore1

Page 34: Chapter 2 Simple Programs. © Judith Bishop 2001 2 Contents 2.1 Three starter programs 2.2 The structure of a program 2.3 Basics of object orientation

© Judith Bishop 200134

Model of the Welcome program

instantiates

Welcome

main

Create the objectrepresenting theprogram

: Welcome

Welcome()

System.out.println(…);

expand

s

Page 35: Chapter 2 Simple Programs. © Judith Bishop 2001 2 Contents 2.1 Three starter programs 2.2 The structure of a program 2.3 Basics of object orientation

© Judith Bishop 200135

Accessing members of an object

Members are methods and variables Accessing members of the object itself is done directly Example name = p; Accessing members from another other object is done

via dot notation

Accessing members of an object objectid.variableid

objectid.methodid ( )

objectid.methodid(parameters

Examples mugs.name

tshirts.write()

Page 36: Chapter 2 Simple Programs. © Judith Bishop 2001 2 Contents 2.1 Three starter programs 2.2 The structure of a program 2.3 Basics of object orientation

© Judith Bishop 200136

Constructors and their parameters

Three distinct roles: performs work of a program when the class has a main

method, e.g. Welcome and CurioStore; creating a graphic user interface if the program

involves graphics, e.g. DrawFlag; copy the initial values when the class is a descriptive

one for the creation of several objects, e.g. as in Curio

Example of initial values

mugs = new Curio("Traditional mugs", 6,

"beaded in Ndebele style");

Page 37: Chapter 2 Simple Programs. © Judith Bishop 2001 2 Contents 2.1 Three starter programs 2.2 The structure of a program 2.3 Basics of object orientation

© Judith Bishop 200137

2.3 Beginning with output

Page 38: Chapter 2 Simple Programs. © Judith Bishop 2001 2 Contents 2.1 Three starter programs 2.2 The structure of a program 2.3 Basics of object orientation

© Judith Bishop 200138

Output statements

Output statements System.out.println (string);

System.out.println (string1 + string2 + ... + stringn);

System.out.println ( );

System.out.print (string);

System.out.print (string1 + string2 + ... + stringn);

Println outputs the string or list of strings and ends the line out of ouput.

Print does not end the line.

Println on its own gives the effect of ending or skipping a line.

System.out.println

A built-in class a built-in object a method of out

Page 39: Chapter 2 Simple Programs. © Judith Bishop 2001 2 Contents 2.1 Three starter programs 2.2 The structure of a program 2.3 Basics of object orientation

© Judith Bishop 200139

Strings for printing

A string literal is any sequence of characters in quotes"sizes M to XL"Licence No. CFD678GT" "€5.95 per kg"

Special effects in strings print stays on the same line, println ends the line \n also ends a line, \t causes a tab \ is an escape character generally so that “ can be printed i.e. \”

System.out.print("€5.95 \nper kg");

System.out.println(”, but he said \"No\"");

€ 5.95

per kg, but he said "No"

Page 40: Chapter 2 Simple Programs. © Judith Bishop 2001 2 Contents 2.1 Three starter programs 2.2 The structure of a program 2.3 Basics of object orientation

© Judith Bishop 200140

Concatenation

Strings must fit on a line Longer strings or lines with several items can be joined

with plus +

System.out.println("Items\tPrice per item");

System.out.println("-----------------------”+

"---------------");

System.out.println(tshirts.name + "\t " + mugs.price);

System.out.println(masks.name + "\t " + masks.price);

Items Price per item

---------------------------

T-shirts 30

Masks 80

Page 41: Chapter 2 Simple Programs. © Judith Bishop 2001 2 Contents 2.1 Three starter programs 2.2 The structure of a program 2.3 Basics of object orientation

© Judith Bishop 200141

Primitive Types and Variables

Every variable has a type and variables of different types cannot be used together

Variables can be of object types (such as mugs being an object variable of type Curio) or primitive types such as int

Variables may be declared anywhere in a Java block - class, method or any group of statements delimited by { and }.

Usually declarations are grouped at the beginning or end of the block.

Identifiers may not be duplicated in a block.

Page 42: Chapter 2 Simple Programs. © Judith Bishop 2001 2 Contents 2.1 Three starter programs 2.2 The structure of a program 2.3 Basics of object orientation

© Judith Bishop 200142

Declaring primitive variables

Primitive variable declarationtype id;type id1, id2, ... idn;type id = value;

int temperature; // in degrees Celsius

int oldWeight, newWeight; // in kilograms

int price; // in graz

int maxMark = 100;

All variables in Java have initial values, e.g. zero for numbers, null for object variables including strings

Page 43: Chapter 2 Simple Programs. © Judith Bishop 2001 2 Contents 2.1 Three starter programs 2.2 The structure of a program 2.3 Basics of object orientation

© Judith Bishop 200143

Expressions

Expression is the term given to formulae in programming languages.

Expressions consist of operands which are numbers, strings or variables, and operators

formula expression in Java

euros/rate

(30*test+20*project+50*exam)/100

euro

rate

30t 20p 50e

100

Page 44: Chapter 2 Simple Programs. © Judith Bishop 2001 2 Contents 2.1 Three starter programs 2.2 The structure of a program 2.3 Basics of object orientation

© Judith Bishop 200144

Division and modulus

In Java the division operator works at two levels: integer and real.

If both the values are integer, it performs integer division, otherwise it performs real division.

Examples16/5 gives 3

16/5.0 gives 3.2 The remainder after integer division or modulus is

represented by %. Examples23 % 2 gives 1

6 % 6 gives 0

81 % 11 gives 4

Page 45: Chapter 2 Simple Programs. © Judith Bishop 2001 2 Contents 2.1 Three starter programs 2.2 The structure of a program 2.3 Basics of object orientation

© Judith Bishop 200145

Assignment

Assignment statement

variable = expression; variable ++;variable --;variable op= expression;

Assignment requires that the type of the expression and the type of the variable are the same.

Example 1int mark = 30*test+20*project+50*exam)/100;

The value of the expression is calculated, and assigned to the variable mark.

Page 46: Chapter 2 Simple Programs. © Judith Bishop 2001 2 Contents 2.1 Three starter programs 2.2 The structure of a program 2.3 Basics of object orientation

© Judith Bishop 200146

More examples of assignment

Example 2oldWeight = 65;

newWeight = oldWeight – 5;

Example 3 - assigning objectsmugs = new Curios("Traditional mugs", 6,

"beaded in Ndebele style");

Curio mostPopular = mugs;

oldWeight = 65

newWeight = 60

mugsmostPopular

mugs

Page 47: Chapter 2 Simple Programs. © Judith Bishop 2001 2 Contents 2.1 Three starter programs 2.2 The structure of a program 2.3 Basics of object orientation

© Judith Bishop 200147

Autoincrement and autodecrement

i++ or i+=1 mean the same thing: ‘add 1 to i’, i+=2 means ‘add 2 to i’, and so on.

Example 1 - to add oneint total;

total = total + 1; // old style

total++; // new style

Example 2 - to subtract 5total -= 5; // add 5 to total

Example 3 - doubling a valueint power;

power *= 2;

Page 48: Chapter 2 Simple Programs. © Judith Bishop 2001 2 Contents 2.1 Three starter programs 2.2 The structure of a program 2.3 Basics of object orientation

© Judith Bishop 200148

Precedence

There are precedence groups for arithmetic operators, with operators within a group being evaluated from left to right

group 0 highest ( )group 1 ++ –– + (unary) – (unary)group 2 * / %group 3 lowest + – + (concatenation)

Examples(temp - 32) * 9 / 5.0b * b - 4 * a * c

Page 49: Chapter 2 Simple Programs. © Judith Bishop 2001 2 Contents 2.1 Three starter programs 2.2 The structure of a program 2.3 Basics of object orientation

© Judith Bishop 200149

Printing expressions

It is possible to print numbers and, indeed, to print the results of expressions.

Exampleint hoursPerDay = 24;

System.out.println (7 * hoursPerDay);

168

The number is printed with exactly as many digits as needed.

If more careful formatting is required, there are additional Java utilities (Chaps 4 and 7)

Page 50: Chapter 2 Simple Programs. © Judith Bishop 2001 2 Contents 2.1 Three starter programs 2.2 The structure of a program 2.3 Basics of object orientation

© Judith Bishop 200150

Several strings and expressions can be printed out in one print if they are joined by the concatenate operator.

Explanation The concatenate operator joins strings. If an operand is not a string, it is converted to one. Classes such as Curio can define toString methods which will be

called before the + is attempted. Concatenation and printing then proceeds.

ExampleSystem.out.println (7 + " days is " +

(7 * hoursPerDay) + " hours");

7 days is 168 hours

Printing numbers and strings

Why brackets?

Page 51: Chapter 2 Simple Programs. © Judith Bishop 2001 2 Contents 2.1 Three starter programs 2.2 The structure of a program 2.3 Basics of object orientation

© Judith Bishop 200151

Example 2.2 Fleet timetables

Problem   How do faster vehicles affect journey times?

Solution   Times are represented in a 24 hour clock, such as 0930 or 1755. There is an average reduction in the journey time of 15%. How to do arithmetic on times?

Algorithm New fleet

      Set up the departure and arrival times

      Calculate journey time in minutes

      Reduce journey time by 15%

      Set new arrival time to the new journey time plus the departure time

      Print out new journey time and new arrival time.

Page 52: Chapter 2 Simple Programs. © Judith Bishop 2001 2 Contents 2.1 Three starter programs 2.2 The structure of a program 2.3 Basics of object orientation

© Judith Bishop 200152

24 hour clock conversions

Convert to minutes

Time is 0715

Find hours from time / 100 7

Find minutes from time modulo 100 15

Set minutes to hours * 60 + minutes 435

Convert to hours and minutes

Minutes are 435

Set hours to minutes / 60 7

Set minutes from minutes modulo 60 15

Set time to hours*100+minutes 715

Page 53: Chapter 2 Simple Programs. © Judith Bishop 2001 2 Contents 2.1 Three starter programs 2.2 The structure of a program 2.3 Basics of object orientation

© Judith Bishop 200153

Program - the declarations

class FleetCalculator { FleetCalculator ( ) { int reduction = 85; int depart24 = 900; int arrive24 = 1020; int newArrive24, // 24 hour clock time departMins, // minutes in a day arriveMins, oldJourneyMins, newJourneyMins, newArriveMins;

Page 54: Chapter 2 Simple Programs. © Judith Bishop 2001 2 Contents 2.1 Three starter programs 2.2 The structure of a program 2.3 Basics of object orientation

© Judith Bishop 200154

Program - Calculations

// convert the initial times to minutes departMins = depart24/100*60 + depart24%100; arriveMins = arrive24/100*60 + arrive24%100; // calculate the old and new times oldJourneyMins = arriveMins - departMins; newJourneyMins = oldJourneyMins*reduction/100; // create the new arrival time in minutes and// then in a 24 hour clock time newArriveMins = departMins + newJourneyMins; newArrive24 = newArriveMins/60*100 + newArriveMins%60;

Page 55: Chapter 2 Simple Programs. © Judith Bishop 2001 2 Contents 2.1 Three starter programs 2.2 The structure of a program 2.3 Basics of object orientation

© Judith Bishop 200155

Program - printing the results

// Report on the findings System.out.println("Departure time is ” +

depart24); System.out.println("Old arrival time is "+arrive24); System.out.println("Old journey time is " +oldJourneyMins+" minutes"); System.out.println("New journey time is " +newJourneyMins+" minutes"); System.out.println("New arrival time is ” +newArrive24); } // and the main method public static void main (String[] args) { new FleetCalculator ( ); } }

Page 56: Chapter 2 Simple Programs. © Judith Bishop 2001 2 Contents 2.1 Three starter programs 2.2 The structure of a program 2.3 Basics of object orientation

© Judith Bishop 200156

Program - the output

Departure time is 900

Old arrival time is 1020

Old journey time is 80 minutes

New journey time is 68 minutes

New arrival time is 1008

Page 57: Chapter 2 Simple Programs. © Judith Bishop 2001 2 Contents 2.1 Three starter programs 2.2 The structure of a program 2.3 Basics of object orientation

© Judith Bishop 200157

About testing

Use a sequence of test values varying one and keep the others static, then move on to vary the next value.

Errors in programs usually occur on boundary values, such as zero, or the last possible value.

Include completely unexpected values, such as a negative percentage or an arrival time before the departure time.

% depart24 arrive24 comment

0 900 1020

115 900 1020 new cars are slower

1 900 1020 small percentages

85 1019 1020 short journey times

85 1100 1020 incorrect departure

85 2400 1020 last possible 24 time

Page 58: Chapter 2 Simple Programs. © Judith Bishop 2001 2 Contents 2.1 Three starter programs 2.2 The structure of a program 2.3 Basics of object orientation

© Judith Bishop 200158

Summary

Keywords class new int null

Syntactic and semantic forms Simple program Declaration of an object

variable Instantiation of an object Accessing members of an

object Output statements Primitive variable calculation Assignment statement Operator precedence

(arithmetic)

Classes, objects and methods from Java’s packages System.out.println System.out.print toString String

Model diagram notation class object object variable primitive variable method instantiation reference method expansion

Page 59: Chapter 2 Simple Programs. © Judith Bishop 2001 2 Contents 2.1 Three starter programs 2.2 The structure of a program 2.3 Basics of object orientation

© Judith Bishop 200159

Quick quiz questions

1. When the Welcome program is run, the first statement to be executed is

A. the constructor B. System.out.println(“Welcome to Java!”);

B. new Welcome(); C. the main method

2. To insert a newline between the printing of two values using println, we need

A. + “n” + B. newline()

B. “\n” D. + “\n” +

3. To add 10 to points, we’d use:A. points + 10 B. points += 10

C. points =+ 10 D. points ++ 10

4. If newArriveMins has the value 310, what will the formula for computing the 24 hour clock tie in Example 3.1 give:

A. 510 B. 610

C. 505 D. 516