Answer:
The Java code for the function as mentioned in the question is shown below.
public void input( int a[], int l )
{
Scanner sc = new Scanner( System.in );
int d;
System.out.println( "Enter the elements in the array" );
for( int k=0; k<l; k++ )
{
d = sc.nextInt();
while( d<-100 || d>100 )
{
System.out.println( "Invalid input. Enter any number from -100 to 100" );
d = sc.nextInt();
}
a[k] = d;
}
}
Step-by-step explanation:
The method takes two parameters – integer array a and integer variable storing the length of the array, l.
This function is supposed to take user input to fill the array with valid input only.
1. To enable user input, object of Scanner class, sc, is created. This is needed since scanner object created in main method cannot be used in other functions of the same class.
Scanner sc = new Scanner( System.in );
2. An integer variable, d, is declared to hold the user input.
3. User is prompted to enter values for the array and inside for loop, user input is taken. The for loop executes over integer variable k till k reaches the length of the array, l-1.
for( int k=0; k<l; k++ )
{
d = sc.nextInt();
while( d<-100 || d>100 )
{
System.out.println( "Invalid input. Enter any number from -100 to 100" );
d = sc.nextInt();
}
a[k] = d;
}
a. After initialization with the value entered by the user, d is tested for validity.
b. The user input for d is tested inside a while loop. This while loop lies inside the for loop.
i. If the value of d lies out of the range beginning from -100 and ending with 100, user is prompted with an error message and asked to enter the value again.
ii. If the variable d holds a valid input, while loop is terminated for that value of d and k.
4. The value of d is assigned to the array.