Java Reference
In-Depth Information
EXAMPLE 9-5
To access the methods to process a one-dimensional array conveniently, we create the
class OneDimArrayMethods and put these methods in this class.
// This class contains methods to manipulate data in a
// one-dimensional array.
import java.util.*;
public class OneDimArrayMethods
{
//Method to input data and store in an int array.
//The array to store the data and its size are passed as
//parameters. The parameter numOfElements specifies the
//number of elements to be read.
public static void fillArray( int [] list, int numOfElements)
{
Scanner console = new Scanner(System.in);
for ( int index = 0; index < numOfElements; index++)
list[index] = console.nextInt();
}
//Method to print the elements of an int array.
//The array to be printed and the number of elements are
//passed as parameters. The parameter numOfElements
//specifies the number of elements to be printed.
public static void printArray( int [] list, int numOfElements)
{
for ( int index = 0; index < numOfElements; index++)
System.out.print(list[index] + " ");
}
//Method to find and return the sum of the elements of an
//int array. The parameter numOfElements specifies the
//number of elements to be added.
public static int sumArray( int [] list, int numOfElements)
{
int sum = 0;
for ( int index = 0; index < numOfElements; index++)
sum = sum + list[index];
return sum;
}
//Method to find and return the index of the first occurrence
//of the largest element, if it repeats, in an int array.
//The parameter numOfElements specifies the number of
//elements in the array.
public static int indexLargestElement( int [] list,
int numOfElements)
Search WWH ::




Custom Search