Answered step by step
Verified Expert Solution
Question
1 Approved Answer
Assignment A3 (45 marks) Focus: Exception Handling, Text I/O Q1. [15 marks] Write a program that creates an integer array with 50 random values, prompts
Assignment A3 (45 marks) Focus: Exception Handling, Text I/O Q1. [15 marks] Write a 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 Sample run Enter an index: 77 Out of Bound. Try again:98 Out of Bound. Try again:43 The element is 4 Q2. [10 marks] "An InputMismatchException is thrown by a Scanner to indicate that the token retrieved does not match the pattern for the expected type, or that the token is out of range for the expected type". For example, if you use the nextDouble to read a token that is not of the type double Write a program that prompts the user to enter a mathematical formula (e.g., 4.3 + 5.1) and then displays the result. Your program should prompt the user to try again if the input has an invalid number or invalid operator (i.e., valid operators are: +, -, /, and ). Assume the user enters spaces between the operands and the operator. Read the numbers using the Scanner's nextDouble method, and the operator using the next method Hints . Use a while loop that will keep prompting the user for input as long as it is invalid . Use a try-catch statement to check for the numbers' validity . Use a selection statement (e.g., if, switch, etc.) to check for the operator's validity Sample run Enter a simple mathematical formula: 4.5 plus 5.3 Invalid Operator. Try again. 4.5a+5.3 Invalid number format. Try again 4.5 +5.3 Result: 9.8 Q3. [10 marks] Repeat Q2 using the Scanner's next method to read the numbers as strings and then convert them to double using Double.parseDouble (). Run your program again and enter an invalid number (e.g., 4.5a). What is the type of Exception that is thrown? When does this exception happen? Modify your code to catch and handle the new exception
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started