Methods

OliverE

Power member.
Reputation
0
Methods
We use methods to hold segments of code that we would usually have to repeat without them.
For example, instead of writing multiple lines of code that all times a number by 2. You can create a method that inputs the number you want to, do the calculations and return the answer. Overall reducing the amount of code you have and making your main method much neater.

Example 1
This example has multiple methods, one for a line, one for the calculations and the main method which just contains the number we wish to do the calculations on.
Notice how little code is used in the main method.
[java]public class SalaryTable
{
public static void underline()
{
System.out.println ("----------------") ;
}
public static void calcAndDisplayRow ( int annualSalary )
{
int perMonth = annualSalary / 12 ;
int perWeek = annualSalary / 52 ;
System.out.println( annualSalary + " " + perMonth + " " + perWeek ) ;
underline();
}
public static void main ( String [ ] args )
{
underline();
calcAndDisplayRow(10000);
calcAndDisplayRow(12500);
calcAndDisplayRow(16000);
calcAndDisplayRow(20000);
}
}[/java]

Example 2
This example is slightly different. It contains a return function.
Try and work out what its doing.
[java]import java.util.*;
public class sumup {
public static void main( String args [] )
{
int number, sum;
Scanner sc = new Scanner(System.in);
sum = 0;
number = sc.nextInt ();
int total = sumUp(number,sum);
System.out.println(total);
}
public static int sumUp(int numb, int total)
// pre: total is zero
// post: total is the sum of integers 1 through numb
{
int i;
for (i = 1; i <= numb; i++) {
total += i;
}
return total;
}
} [/java]

Let me know if you have any questions.
 
Back
Top