Example of a method:
The codes:
import java.util.Scanner; public class Sum { public static void main(String[] args) { Scanner input = new Scanner(System.in); int [] A = {7,3,6,9,1,2,8,5,0,4}; int [] B = new int[5]; System.out.println("Enter 5 numbers."); for(int i=0; i < 5; i++) B[i]=input.nextInt(); int maxA = getMax(A); //Save a return value in a variable //print it after you save the result System.out.printf("The maximum of A array is %d.\n", maxA); //You can call a method and print the return value immediately System.out.printf("The maximum of B array is %d.\n", getMax(B)); } /** Client provide any int array with any length getMax method will find the max number from the array and return it to client. */ public static int getMax(int[] arr) { int n = arr.length; //the number of elements in arr int max = arr[0]; //initialize max as the first element for(int i=1; i<n; i++) //Check from the second element { if(arr[i] > max) //if element is larger than max, max = arr[i]; //overwrite the max } return max; } }
Adding two more methods as below:
Call from main method:
The code:
public static int getSum(int[] x) { int n = x.length; int sum = 0; for(int i=0; i<n; i++) sum +=x[i]; return sum; } public static double getAvg(int[] y) { int n = y.length; int sum = getSum(y); double avg = (double) sum / n; return avg; }