In Java Write an application named GoTooFar in which you declare an array of fiv
ID: 3629699 • Letter: I
Question
In JavaWrite an application named GoTooFar in which you declare an array of five integers and store five values in the array. Write a try block in which you loop to display each successive element of the array, increasing a subscript by 1 on each pass through the loop. Create a catch block that catches the eventual ArrayIndexOutOfBoundsException and display the message, "Now you've gone too far".
No errors, except it has to be stopped manually
Thanks
[code]
public class GoTooFar
{
public static void main(String[] args)
{
int a = 0;
int[] n = {1,2,3,4,5};
boolean done = false;
while (done == false)
{
try
{
while (true)
{
System.out.println("(" + a + ") " + n[a]); a++;
}
}
catch (ArrayIndexOutOfBoundsException error)
{//<editor-fold defaultstate="collapsed" desc="Catchblock">
//</editor-fold>
System.out.println("Now you've gone too far.");
}
}
}
}
[code]
Explanation / Answer
simple, include done = true after the system.out.print statement (this will stop after the first execution of the arrat index out of bounds exception) as follows: public static void main(String[] args) { int a = 0; int[] n = { 1, 2, 3, 4, 5 }; boolean done = false; while (done == false) { try { while (true) { System.out.println("(" + a + ") " + n[a]); a++; } } catch (ArrayIndexOutOfBoundsException error) {// // System.out.println("Now you've gone too far."); done = true; } } }Related Questions
Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.