Upload
wilfred-powers
View
214
Download
0
Embed Size (px)
Citation preview
19/04/23 SJF L4 1
F21SFSoftware Engineering Foundations
4 More Programming concepts
Using the Car class
Constants, Math class, boolean, formattingSELECTION
Monica Farrow EM G30 email : [email protected] available on Vision
Dept ofComputerScience
19/04/23 SJF L4 2
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
19/04/23 SJF L4 3
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.
19/04/23 SJF L4 4
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
myCar
model “Ford Ka”
tankSize 40
manfMPG 33.6
19/04/23 SJF L4 5
Multiple objects
In the Car class, we can create 2 cars and compare how far they can travelCar 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);
19/04/23 SJF L4 6
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
19/04/23 SJF L4 7
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
19/04/23 SJF L4 8
Class Constants
Insert these lines just after the instance variables//gallons per litreprivate static final double GPL=0.22;
Use instead of 0.22return tankSize * manfMPG * GPL;
private static final double GPL= 0.22;
Never changes during the program
Independent of specific objects of the class- The same for all Car objects
Use capitals by convention
19/04/23 SJF L4 9
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
19/04/23 SJF L4 10
Math abs method - documentation
We’ll use the abs method to disregard the sign when printing the difference in distance
Here is the java documentation on the method
abs(double a) Returns the absolute value of a double value.
static
double
Method name and link to slightly fuller description
Parameters incl type
Return type
Indep of obj
Description
19/04/23 SJF L4 11
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
19/04/23 SJF L4 12
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
19/04/23 SJF L4 13
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 classdouble squareRoot = Math.sqrt(45);
19/04/23 SJF L4 14
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)
19/04/23 SJF L4 15
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..)
19/04/23 SJF L4 16
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.
19/04/23 SJF L4 17
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
19/04/23 SJF L4 18
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
19/04/23 SJF L4 19
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");
19/04/23 SJF L4 20
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);
19/04/23 SJF L4 21
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.
19/04/23 SJF L4 22
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
19/04/23 SJF L4 23
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
19/04/23 SJF L4 24
Output text for 1st car up to ‘which is’ = 1
result = counter * resultcounter += 1
[n== 0, n== 1]
[counter <=n]
Output ‘ miles less than the’ )
Output text for 2nd car
Output absolute diff and ‘miles’= 1
Output ‘ miles more than the’
[2nd car dist < 1st car dist] [1st car dist < 2nd car dist]
[= dist]
Output ‘ the same as the’
Shows actions, transition lines, decision diamonds with conditions,and merge diamonds,
19/04/23 SJF L4 25
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 ";
19/04/23 SJF L4 26
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() );
19/04/23 SJF L4 27
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
19/04/23 SJF L4 28
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.)
19/04/23 SJF L4 29
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
19/04/23 SJF L4 30
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;
}
19/04/23 SJF L4 31
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
19/04/23 SJF L4 32
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
19/04/23 SJF L4 33
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;
19/04/23 SJF L4 34
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; }
19/04/23 SJF L4 35
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
19/04/23 SJF L4 36
(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;
19/04/23 SJF L4 37
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.