Functions

A function that returns a double value can be used any place a double value can be used.

The program asks the user to enter a number, then a function is used to find half of the number.

In the first program the value returned by the function is stored in a variable. In the second program, the returned value is printed directly.

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