Before you do this section, watch the videos here: https://www.dropbox.com/sh/v0xcqgjkia6brmm/AABRKcrZjwhkR1j14NsMcd4za?dl=0
Older programming languages distinguish between Functions and Procedures. Very simply, a function returns a value, a procedure does not.
Java rolls both of these into one concept: Methods. A method always has a return type. If the return type is void it is what an older language would call a procedure, otherwise it’s a function.
Here is an example method:
public void spoons (String s, int i)
Access Type | Return Type | Name | Parameters |
public | void | spoons | (String s, int i) |
---|
Two example Classes
public class Main {
public static void main(String[] args)
{
Person p1 = new Person("Bloggs", "Joe");
p1.setSex("M");
Person p2 = new Person("Baker", "Jill");
p2.setGender("F");
p1.printPerson();
p2.printPerson();
}
}
public class Person {
private String surname;
private String forename;
private String gender;
Person(String surname, String forename)
{
this.surname = surname;
this.forename = forename;
}
public void setGender(String s)
{
if(!(s.equals("F")|s.equals("M")))
{
System.out.println("Validation error!");
} else
{
sex = s;
}
}
public void printPerson()
{
System.out.println(surname + " " + forename + " " + gender);
}
}
Method Exercise: Progress Tracker
Write a class Pupil that will track pupils’ progress through a year. The class will store pupils’ grades as percentages.
- Add private member variables String forename, surname
- Add private member variables int target, autumn, spring, summer
- Add a constructor method that will accept the parameters forename, surname, target
- Test the constructor by adding the following pupils: Joe, Bloggs, 70 and Jill, Cooper, 75
- Add accessor methods to setAutumn(), setSpring(), setSummer()
- Add accessor methods to getAutumn(), getSpring(), getSummer()
- Add the following grades to Joe Bloggs: Autumn 55, Spring 65, Summer 75
- Add the following grades to JIll Cooper: Autumn 50, Spring 60, Summer 70
- Add a method average() to return a double showing the average percentage a pupil has. Print out Joe and Jill’s average scores
- Add a method progress() that will return a String saying whether the pupil is above target, on target or below target on the summer test.
- Check this method works on Joe and Jill
- Add a print() method that will print out the pupil’s details in a suitable format
Extension Work
- Add a validation() method to check that grades entered lie between 1 and 100
- Modify your average() method so it will return a correct average if only one or two grades have been entered so far
- Add a static int variable aBound to record the grade A boundary.
- Add the appropriate setters and getters to aBound
- Set up a Pupil [] array in your Main class to handle your pupils
- Add a save() method to your Pupil class that will write the pupil data to file