Functions

Because execution starts with main, many programmers prefer to show main first and the other functions after that. Notice that the function is inside the class.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
package numbers;
import java.util.*;
public class Numbers {
  public static void main(String[] args) {
	  Scanner keyboard=new Scanner(System.in); //do just once
	  double num;
	  System.out.print("Enter a number:");;
	  num=keyboard.nextDouble();
	  System.out.println("Half is "+half(num));
  }//main
  public static double half(double num){
	  return num/2.0;
  }//half
}//class
CODE

Sample output:

Enter a number:7
Half is 3.5

Enter a number:34.25
Half is 17.125

* We would not really write a function called half. It is much simpler to just use num/2.

NEXT: