4 more programming concepts using the car class constants math class boolean formatting selection
Download
1 / 37

F21SF Software Engineering Foundations - PowerPoint PPT Presentation


  • 93 Views
  • Uploaded on

4 More Programming concepts Using the Car class Constants, Math class, boolean, formatting SELECTION. Dept of Computer Science. F21SF Software Engineering Foundations. Monica Farrow EM G30 email : [email protected] Material available on Vision. Topics.

loader
I am the owner, or an agent authorized to act on behalf of the owner, of the copyrighted work described.
capcha
Download Presentation

PowerPoint Slideshow about ' F21SF Software Engineering Foundations' - micol


An Image/Link below is provided (as is) to download presentation

Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author.While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server.


- - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - -
Presentation Transcript
4 more programming concepts using the car class constants math class boolean formatting selection

SJF L4

4

More Programming concepts

Using the Car class

Constants, Math class, boolean, formattingSELECTION

Dept of

Computer

Science

F21SFSoftware Engineering Foundations

Monica Farrow EM G30

email : [email protected]

Material available on Vision


Topics

SJF L4

Topics

  • Improving car comparisons using

    • Class constants

    • Math class including the abs function

    • If/else

  • Including

    • The word ‘static’

    • Algorithm

    • Boolean expressions

    • Formatting output

    • Scope


Multiple objects

SJF L4

Multiple objects

  • There are (at least) 2 advantages to dividing a program into classes

    • The program is modular, with everything connected with a particular object in one place

    • If the program contains multiple objects of the same type (e.g. more than one car), the methods in the Car class are only written once, but can be used with each Car object. This can reduce code duplication.


Multiple objects1

SJF L4

myCar

model

“Ford Ka”

tankSize

40

manfMPG

33.6

Multiple objects

  • One Car class, many objects

    • Each object has its own instance variables

    • Each object can use the class’s methods

yourCar

model

“Mercedes....”

tankSize

65

manfMPG

22


Multiple objects2

SJF L4

Multiple objects

  • In the Car class, we can create 2 cars and compare how far they can travel

    Car myCar = new Car("Ford Ka", 40, 33.6);

    Car yourCar = new Car

    ("Mercedes Benz E280", 65, 22);

    double myDist = myCar.estimateDistance();

    double yourDist =

    yourCar.estimateDistance();

    double difference = myDist – yourDist;

    System.out.println ("Diff is " + difference);


Issues arising

SJF L4

Issues arising

Output:Diff is -18.920000000000016

Using raw numbers (0.22 for gallons per litre) is often bad style

Use constants

We’d like to print out values to one decimal point

Format the output

If we don’t know which car goes further, we might print out a negative difference.

Use an ‘absolute value’ function in the Math class

A slightly more meaningful message would be nice

Use if/else structures


No magic numbers

SJF L4

No magic numbers!

To convert the manufacturer’s MPG to MPL, we need to multiply by 0.22.

We might want to use the conversion factor elsewhere in the class, not just in one method

We should declare it with the instance variables, then it can be used anywhere in the class, and it’s obvious what the number is

The instance variables model, tank size and mpl will vary with each type of car

The conversion factor 0.22 is fixed and will never change for ANY car


Class constants

SJF L4

Class Constants

Insert these lines just after the instance variables

//gallons per litre

private static final double GPL=0.22;

Use instead of 0.22

return tankSize * manfMPG * GPL;

Never changes during the program

Use capitals by convention

private static final double GPL= 0.22;

Independent of specific objects of the class

- The same for all Car objects


Math class

SJF L4

Math class

The Math class contains a collection of mathematical methods and constants

Rounding, power, absolute value, sin/cos, pi etc (The absolute value of a number is the numerical value, disregarding the sign. E.g. it is 4 for both 4 and -4)

It is in the java.lang package and so is available to all java programs


Math abs method documentation

SJF L4

Math abs method - documentation

Method name and link to slightly fuller description

Parameters incl type

Indep of obj

static 

double

abs(double a) Returns the absolute value of a double value.

Return type

Description

  • We’ll use the abs method to disregard the sign when printing the difference in distance

  • Here is the java documentation on the method


Math abs method using

SJF L4

Math abs method - using

  • We use it like this:

    double absDiff = Math.abs(myDist - yourDist);

    Ststem.out.print(“Difference is “ +

    absDiff);

  • Math methods are all static methods

    • i.e. independent of a particular object

    • No need to instantiate a Math object

    • Call using the name of the class before the period


Calling methods for an object

SJF L4

Calling methods for an object

  • Usually, methods are Instance methods associated with an object, which use the values stored in the instance variables belonging to that object. Call using the object name and a full stop (period).

    • myCar.estimateDistance() uses the value of tankSize associated with the myCar object

    • yourCar.estimateDistance() uses the value of tankSize associated with the yourCar object


Calling static methods

SJF L4

Calling static methods

  • Static methods typically take data from parameters and compute a value, like a maths function.

  • They use no instance variables of any object of the class they are defined in. Just call using the name of the class

    double squareRoot = Math.sqrt(45);


Static

SJF L4

static

  • ‘static’ means that it is independent of particular objects of that class

    • It is used for class constants e.g. GPL

    • It is used for the ‘main’ method, which is not related to any objects

      public static void main (String arg[])

    • All methods in the Math class are static – you can’t make a Math object.

    • The String class has some static methods (e.g. format, which returns a String, introduced next) and many instance methods (e.g. equals, charAt etc)


A program may contain these classes

SJF L4

A Program may contain these classes

  • A class containing the main method

    • Essential. The program starts here. We will use this in a class by itself. It could be used within an object class.

  • Object classes that

    • Either we write ourselves e.g. Person, Car, Name

    • Or are supplied as part of the java API e.g. for collections, for GUIs, for random numbers, etc.

  • Static classes

    • These are independent of an individual object E.g. Math – a collection of useful functions (rounding, squaring..)


Formatting output

SJF L4

Formatting output

  • When printing the distance a car can travel, it’s not possible using the System.out.println method to control the number of decimal places that are displayed.

  • Originally, input and output was poorly provided for in java, and all textbook writers and many university departments wrote their own classes!

  • Now there are formatting features similar to C, which look complicated. You specify the type and the spacing.


Formatting output1

SJF L4

Formatting output

  • This lecture covers the absolute minimum for printing a number within a sentence.

  • The lecture Formatting.ppt covers this and more details for later, for printing numbers, characters and Strings in a table.

  • There is a static format method within the String class.

    • Call using the class name, like a Math function

    • The parameters are formatting instructions and the item to be formatted.

    • A formatted String is returned


Formatting real numbers

SJF L4

Formatting real numbers

  • In the String format method, the value of the 2nd parameter is returned using the format specified in the 1st parameter

    String myDistString = String.format("%.1f", distance);

    If distance contained a double of 296.6666recurring, myDistString = “296.7”

  • "%.1f" means format a real number to 1 decimal place

    • % means the string contains formatting information

    • .1 is the number of decimal places after the .

    • f means it is a real number


Car formatted output

SJF L4

Car formatted output

//get estimated distance

double distance = myCar.estimateDistance();

//get distance as a string to 1 decimal place

String myDistString

= String.format("%.1f", distance);

//print the details to standard output

System.out.println(model + " can travel "

+ myDistString + " miles");


Formatting the absolute difference

SJF L4

Formatting the absolute difference

  • Similarly, we can format the absolute difference in distance:

    double absDiff = Math.abs(myDist-yourDist);String absString =

    String.format(“%.1f”, absDiff);

    System.out.print(“Difference is “ +

    absString);


Selection

SJF L4

SELECTION

  • To improve our message about different distances, we need to print different text depending on which car can go further.

  • We’d like our code to work in all situations, no matter which 2 cars are compared.

  • Sample textThe Ford Ka can travel 296 miles, which is 19 miles less than the Mercedes Benz E280.


Algorithms

SJF L4

Algorithms

  • It’s often useful to plan using an algorithm (set of instructions).

  • Use programming structures (if, while, for) but keep the rest in English

  • Use indentation in the same way as in code

    • To show what happens inside block


Algorithm for printing the line

SJF L4

Algorithm for printing the line

  • Algorithm (set of instructions) In English, for output

    Output text for first car up to ‘which is’

    Output the absolute difference and ‘miles’If first distance is < second,

    output ‘less’else / otherwise

    output ‘more’Output remaining text for second car.What is the logic error here?!

    Is this the only possible algorithm?


Uml activity diagram

SJF L4

UML Activity diagram

Shows actions,

transition lines,

decision diamonds

with conditions,

and merge diamonds,

Output text for 1st car

up to ‘which is’ = 1

Output absolute diff

and ‘miles’= 1

[2nd car dist < 1st car dist]

[1st car dist < 2nd car dist]

[n== 0, n== 1]

[= dist]

Output ‘ miles less than the’ )

Output ‘ miles more than the’

Output ‘ the same as the’

result = counter * result

counter += 1

[counter <=n]

Output text for 2nd car


If else else statement

SJF L4

If-else-else statement

This if/else-if/else structure allows for 3 alternatives. You can have as many ‘else-if’ blocks as necessary.

String diffMessage = "";

if (myDist < yourDist)

diffMessage = absString

+ " miles less than the ";

else if (myDist > yourDist)

diffMessage = absString

+ " miles more than the ";

else

diffMessage = "the same as the ";


Final output

SJF L4

Final output

//note the insertion of spaces within the string literals where necessary

System.out.println("The "

+ myCar.getModel()

+ " can travel " + myDistString

+ " miles on a full tank, which is "

+ diffMessage + yourCar.getModel() );


Testing the improved car class

SJF L4

Testing the improved Car class

  • We need to make sure that the improvements work in all situations

  • So in the main method, we should

    • Test where the first distance is < the second

    • Test when distances are the same

    • Test when the first distance is > the second

Finishing with a little theory


Boolean expressions

SJF L4

Boolean expressions

Boolean expressions return true or false. The basic operators are

< (less than)

<= (less than or equal to)

> (greater than)

>= (greater than or equal to)

== (equal to) ***

!= (not equal to)

*** Note there are TWO equals signs. (The single = is the assignment operator.)


More about booleans

SJF L4

More about booleans

Sometimes you need to make more than one comparison

E.g. a number is in the range 1 and 12

We can’t write if (0<num<=12)

We have to write “If the number is greater than 0 AND ALSO less than or equal to 12”

if (num > 0 && num<=12)

Comparison operators:

Use && for AND - both conditions must be true

Use || for OR – at least one condition must be true

Use ! for NOT – condition must be false


Boolean type

SJF L4

boolean type

  • boolean is another of the primitive types in java

  • Variables can be declared of type boolean e.g.

    • boolean isEmployee = true;boolean found = false;

  • Methods can return a boolean type e.g.

    //returns true if the tankSize of the car

    //is bigger than that supplied in the parameter, returns false otherwise

    public boolean tankBigger(int tSize) {return tankSize > tSize;

    }


Boolean exercises

SJF L4

Boolean exercises

  • Write boolean expressions (which could go inside the brackets of an if statement), using the variables and methods on the previous slides

    • num is not equal to 6

    • num is not in the range 1-12

    • found is true

    • found is false

    • myCar has a tank bigger than 50

    • myCar has a tank less than or equal to 50


Scope instance variables

SJF L4

Scope – instance variables

  • Instance variables are declared within a class, not within a method

    • they can be used in the constructor and any of the methods in that class

  • If they are declared private, they are not accessible to any other classes

    • Other classes get at this data via ‘get’ methods

    • This is the norm in OOP

    • We will see some variations on this later in the module


Scope local variables

SJF L4

Scope – local variables

  • Variables which are used as useful storage within a method are called local variables

    • they can only be used within the method in which they are declared

    • The main method contains a number of local variables

    • The estimateDistance method could have been written with local variables. This is useful if you want to check values as you go along, either by printing them out or looking at them in a debugger.

      double mpl = manfMPG * GPL;

      double distance = tankSize * mpl;

      return distance;


Scope parameters

SJF L4

Scope – parameters

  • Parameters are like local variables

    • they can only be used inside the method

      public Name(String fName, String mName, String lName) {

      firstName = fName;

      middleName = mName;

      lastName = lName;

      }


Quiz terminology

SJF L4

QUIZ - terminology

  • Given the code on the next slide, can you identify:

    • A local variable

    • A parameter

    • An instance variable

    • A static method call

    • An object

    • A statement

    • A literal

    • Using a constructor


SJF L4

(in a main method)

Car myCar = new Car("Ford Ka", 40, 33.6);

String model = myCar.getModel();

double distance = myCar.estimateDistance();

String myDistString = String.format("%.1f",distance);

. . .

double difference = myDist - yourDist;


To do now

SJF L4

To Do Now

  • Read over lecture, do quizzes

  • Download code and try it out

    • Change it so that the distance for ‘yourCar’ is also formatted.


ad