Question
Java programming: The feedback I received responds badly to bad input. Fix 2 Original question: Write a program that creates a small (6-10) array of
Java programming:
The feedback I received "responds badly to bad input. Fix 2"
Original question:
Write a program that creates a small (6-10) array of ints. Display your array elements, all on one line, using a foreach loop. In a try block, prompt the user to enter an index for the array and attempt to print the element with that index. Follow the try block with two catch blocks; one that detects an index out of bounds, and another that catches other bad inputs. Make sure the catch blocks are properly ordered (see page 464). Include a finally block that reports the size of the array. See Sample Runs below.
Sample Run 1
12 15 24 5 9 16
Enter any index of your array 5
The element at index 5 is 16
The array size is 6
Sample Run 2
12 15 24 5 9 16
Enter any index of your array 9
Error. Array index was out of bounds
The array size is 6
Sample Run 3
12 15 24 5 9 16 12 22
Enter any index of your array three
Bad input. Try again
The array size is 8
______________________________________________________________________________________________
My code:
import java.util.*;
public class Program2 {
public static void main(String[] args) { Scanner input = new Scanner(System.in);
int[] theElements = { 12, 15, 24, 5, 9, 16 };
int j = 1, index = -1;
String select;
while (true) { System.out.println("Sample Run " + j);
System.out.print(Arrays.toString(theElements)); System.out.print(" Enter any index of your array "); try { index = input.nextInt();
} catch (InputMismatchException ex) { System.out.print("Bad input. Try again"); } // for each loop for (int i : theElements) {
if (index > theElements.length || index < 0) { System.out.print(" Error. Array index was out of bounds"); } else {
System.out.print(" The element at index " + index + " is " + theElements[index]); System.out.print(" The array size is " + theElements.length); break; }
} j++; System.out.print(" want to continue (y/n) "); select = input.next();
if (select == "y" || select == "Y") { continue; } else {
break; }
}
}
}
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