|
Java Tutorial |
MoreMethodsThese pages make up the course notes for my Java programming course (run at Dallam, Milnthorpe, Cumbria). Hopefully they also make a useful self-learning tutorial. In the same way that this tutorial is broken into sections and books are split into chapters, when your code becomes long and complex you should split it up to make it easier to read. Another reason for splitting up the code is to save on typing, if you find yourself typing out the same lines of code over and over you can put those lines in their own method and then call that method. Here’s yet another modification to our VatBill example. In that example we had to keep typing System.out.println (or at least I did, you just copied and pasted it!), lets save on a bit of typing. Note:
public class VatBill {
/**
* @param args
*/
public static void main(String[] args) {
float[] items = {4.99f, 7.99f, 9.99f};
float vatRate = 17.5f; //VAT as a percentage
//add up the items to get the net price
int count;
float netPrice = 0;
for (count=0; count<3; count=count+1) {
netPrice = netPrice + items[count];
}
display("The net price is " + netPrice);
// give a 10% discount on amounts more than £20.00
if (netPrice > 20) {
float discount = netPrice * 0.1f;
netPrice = netPrice - discount;
display("You have earned a 10% discount of " + discount);
}
//calculate the amount of VAT on the net price
float vatAmount = vatRate/100 * netPrice;
display("The amount of VAT is " + vatAmount);
//calculate the total price payable
float totalAmount = netPrice + vatAmount;
display("The gross amount (inc VAT) is " + totalAmount);
}
private static void display(String message) {
System.out.println(message);
}
}
What we now have is another method in our VatBill class called display and all the System.out.println statements have been replaced with display . When we use display in the main method, the flow of execution jumps to the display method, executes the code it contains and then jumps back to the main method. There are a few things we need to know about creating another method. As noted above the main method MUST follow a particular structure, or else our program will not run, however other methods can have different keywords, names and arguments depending on what we want them to do. The display method definition looks like this: private static void display(String message) The use of the private keyword means that this method can only be accessed from within this class. This is followed by the static keyword, both the private and static keywords are discussed in more detail later. All methods must have a type (int, float, String, etc), in the same way that variables have a type. Both the main method and our new display method have a type of void . This means that they do not return a value, as we will see shortly, we often want a method to return a value. Next is the name of our method – this can be any name we like as long as it starts with a letter (or _) and only contains letters, numbers and _ The name of the method is followed by brackets () and in those brackets is what is known in the jargon as an argument . Arguments are optional, some methods do not need them. In this method it is a String variable to which we have given the name message which is the text string that we want to display. Obviously the message that we want to display is different every time we call the display method, and so we pass the text String to be displayed to the display method. When we use the display method we use code like
Inside the display method, all we do is use System.out.println (which is what we were doing previously) to print whatever is in the message variable on screen. As an example of creating a method that returns a value lets create one to do the VAT calculation. Currently we apply the 17.5% VAT (UK sales tax) in the body of the main method, but this calculation is one that is done very frequently and so it may be useful to have a method that can do it for us, and even better if it is a method that can be used from anywhere. To do this we need to make a few changes (this kind of thing – deciding to pull a section of code out of a method and put it in its own method - happens quite often and is technically known as refactoring ).
public class VatBill {
/**
* @param args
*/
public static void main(String[] args) {
float[] items = {4.99f, 7.99f, 9.99f};
//add up the items to get the net price
int count;
float netPrice = 0;
for (count=0; count<3; count=count+1) {
netPrice = netPrice + items[count];
}
display("The net price is " + netPrice);
// give a 10% discount on amounts more than £20.00
if (netPrice > 20) {
float discount = netPrice * 0.1f;
netPrice = netPrice - discount;
display("You have earned a 10% discount of " + discount);
}
//calculate the amount of VAT on the net price
float vatAmount = vatAmount(netPrice);
display("The amount of VAT is " + vatAmount);
//calculate the total price payable
float totalAmount = netPrice + vatAmount;
display("The gross amount (inc VAT) is " + totalAmount);
}
/**
* display some text
*
* @param message - the text to display
*/
private static void display(String message) {
System.out.println(message);
}
/**
* calculate the amount of VAT payable
*
* @param netPrice - the amount for which VAT is to be calculated
* @return
*/
public static float vatAmount( float netPrice) {
float vatRate = 17.5f; //VAT as a percentage
float result = vatRate/100 * netPrice;
return result;
}
}
This work is Copyright Chris Hunter 2007, you may use it for non-commercial purposes |