Question

Write a java program that creates an integer array with 50 random values, prompts the user...

Write a java program that creates an integer array with 50 random values, prompts the user to enter the index of an element in the array between 0 and 49, then displays the corresponding element value. If the specified index is out of bounds, display an error message (e.g. “Out of Bounds”) and ask the user to enter another index. Use a while loop that will keep prompting the user until a valid input is received. To handle invalid inputs, write two versions of your program: one that uses exception handling, and one that uses defensive programming. Assume a user will always enter numbers. Verify that the displayed element number is indeed from the index number entered. Add comments.

Sample run:

list[50] of random int generated

14 37 19 98 31 1 68 11 18 90

36 14 37 63 68 54 64 51 80 75

66 85 30 65 97 66 87 47 52 63

9 22 68 70 11 32 23 69 37 12

62 62 76 89 33 0 43 87 30 27

Enter an index: 55

Out of Bound. Try again:50

Out of Bound. Try again:5

The element is 1

Homework Answers

Answer #1

Dear student your solution is below:

====================================================================

Note: Follow the screenshot of program to get the idea about indentation in program.

Comment are written in front of code for better understability of the program.

First program is based on defensive approac.

Second Program uses Exception Handling

------------------------------------------------------------------------------------------------------------------

1. Program in Java: (Defensive Approach)

-----------------------------------

//importing the classes
import java.util.Random;
import java.util.Scanner;

//class
public class Main
{

   //main function
   public static void main(String[] args) {
  
       int list[] = new int[50];
//declearing a list of size 50
       Random r = new Random(); //for generating random number
       Scanner sc = new Scanner(System.in);
       for(int i = 0; i < 50; i++){
       list[i] = r.nextInt(100);
//generating and storing random number in list
       }
      
       int index = -1;
       System.out.print("Enter an Index: ");
//input index from user
       index = sc.nextInt();
      
       //checking and taking input again from user
       while(index < 0 || index > 49){
       System.out.print("Out of Bound. Try Again: ");
       index = sc.nextInt();
       }

      
       sc.close();
       //printing the element at provided index
       System.out.println("The element is " + list[index]);
   }
}// End of program

OUTPUT:

------------------------------------------------------------------------------------------------------------------------------------

2. Java Program (Exception Handling):

-------------------------------------------------------------

//importing the classes
import java.util.Random;
import java.util.Scanner;

//class
public class Main
{

   //main function
   public static void main(String[] args) {
  
       int list[] = new int[50];
//declearing a list of size 50
       Random r = new Random(); //for generating random number
       Scanner sc = new Scanner(System.in);
       for(int i = 0; i < 50; i++){
       list[i] = r.nextInt(100);
//generating and storing random number in list
       }
      
       int index = -1;
       System.out.print("Enter an Index: ");
//input index from user
       index = sc.nextInt();
      
       //checking and taking input again from user with try-catch
       while(true){
       try{

       //printing the element at provided index
       System.out.println("The element is " + list[index]);
      
       //if no exception occour in above statement
       // then break out of the while loop
      
       break;
      
       }catch(ArrayIndexOutOfBoundsException e){
      

       //If exception occour in try block
       System.out.print("Out of Bound. Try Again: ");
       index = sc.nextInt();
       }
       }
   }
}

OUTPUT:

==============================================================================

Hope it has helped you.

==============================================================================

Know the answer?
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for?
Ask your own homework help question
Similar Questions
Write a Java program to randomly create an array of 50 double values. Prompt the user...
Write a Java program to randomly create an array of 50 double values. Prompt the user to enter an index and prints the corresponding array value. Include exception handling that prevents the program from terminating if an out of range index is entered by the user. (HINT: The exception thrown will be ArrayIndexOutOfBounds)
(Python Programming) Write a program that prompts a user for a positive integer and then uses...
(Python Programming) Write a program that prompts a user for a positive integer and then uses a loop to calculate and display the sum of specific fractions as follows: Let's say the user enters 5, then your program will compute: 1/5 + 2/4 + 3/3 + 4/2 + 5/1 which is 8.7.
Write a C program that prompts the user to enter a line of text on the...
Write a C program that prompts the user to enter a line of text on the keyboard then echoes the entire line. The program should continue echoing each line until the user responds to the prompt by not entering any text and hitting the return key. Your program should have two functions, writeStr and readLn, in addition to the main function. The text string itself should be stored in a char array in main. Both functions should operate on NUL-terminated...
Write a program that prompts the user to enter an integer number between 1 and 999....
Write a program that prompts the user to enter an integer number between 1 and 999. The program displays the sum of all digits in the integer if the input is valid; otherwise, it displays a message indicating that the integer is not between 1 and 999 and hence, is invalid. Name the program file Q1.cpp Example: if the user enters 12, sum of digits is 3. If the user enters 122, sum of digits is 5.
Write a program that asks the user to input an integer between 25 and 50, inclusive....
Write a program that asks the user to input an integer between 25 and 50, inclusive. Utilize a WHILE loop to test for INVALID input. If the input is INVALID, the loop will repeat, and ask the user to try again. The pseudocode looks like this: Prompt user to input an integer between 25 and 50 Accept the input from the user Test for invalid input (HINT: use a while loop and the OR operator with 2 relational expressions. You...
Python: Write a program that prompts the user to enter a positive integer value, and compute...
Python: Write a program that prompts the user to enter a positive integer value, and compute the following sequence: • If the value is even, halve it. • If it's odd, multiply by 3 and add 1. • Repeat this process until the value is 1, printing out each value. • Then print out how many of these operations you performed. If the input value is less than 1, print a message containing the word Error and exit the program....
Write a program that prompts the user for the number of values for which it will...
Write a program that prompts the user for the number of values for which it will calculate the base 2 log of each value. Use a for loop to iterate the set of values and print the log for each. Here is the formula to change the base of a log: loga b = log10 b / log10 a Sample output appears below. This program will calculate the Base 2 log of a set of numbers<LINERETURN> ===============================================================<LINERETURN> Enter the upper...
Write a program in C++ coding that asks the user to input an integer between 25...
Write a program in C++ coding that asks the user to input an integer between 25 and 50, inclusive. Utilize a WHILE loop to test for INVALID input. If the input is INVALID, the loop will repeat, and ask the user to try again. The pseudocode looks like this: Prompt user to input an integer between 25 and 50 Accept the input from the user Test for invalid input (HINT: use a while loop and the OR operator with 2...
Write a function in c using #include <stdio.h> that takes a one-dimensional integer array and returns...
Write a function in c using #include <stdio.h> that takes a one-dimensional integer array and returns the index of the first occurance of the smallest value in the array. Your function must be able to process all the elements in the array. Create a function prototype and function definition (after the main function). Your main function should declare a 100 element integer array. Prompt the user for the number of integers to enter and then prompt the user for each...
Using C++, Python, or Java, write a program that: In this programming exercise you will perform...
Using C++, Python, or Java, write a program that: In this programming exercise you will perform an empirical analysis of the QuickSort algorithm to study the actual average case behavior and compare it to the mathematically predicted behavior. That is, you will write a program that counts the number of comparisons performed by QuickSort on an array of a given size. You will run the program on a large number of arrays of a certain size and determine the average...
ADVERTISEMENT
Need Online Homework Help?

Get Answers For Free
Most questions answered within 1 hours.

Ask a Question
ADVERTISEMENT