Ask Question
1 April, 14:10

Write a function to have a user enter some number of integers into an array. The integer values must be between - 100 and + 100 inclusive (+100 and - 100 should be accepted as valid inputs). The integer array and the size of the array are passed into the function through parameters. Do not worry about includes. This is only a function, so there is no main routine. The function should fill the array with valid inputs. For invalid input values, inform the user of the error, but do not count that as a valid input.

+1
Answers (1)
  1. 1 April, 14:34
    0
    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
    {

    d = sc. nextInt ();

    while (d100)

    {

    System. out. println ("Invalid input. Enter any number from - 100 to 100");

    d = sc. nextInt ();

    }

    a[k] = d;

    }

    }

    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
    {

    d = sc. nextInt ();

    while (d100)

    {

    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.
Know the Answer?
Not Sure About the Answer?
Find an answer to your question 👍 “Write a function to have a user enter some number of integers into an array. The integer values must be between - 100 and + 100 inclusive ...” in 📗 Computers & Technology if the answers seem to be not correct or there’s no answer. Try a smart search to find answers to similar questions.
Search for Other Answers