Description
design an application in which you declare an array of three strings and store three values in the array. write a try block in which you loop to display each successive element of the array, increasing a subscript by one on each pass through the loop. assume that an arrayindexoutofboundsexception is created automatically when a subscript is not correct for an array. create a catch block that catches any exception and displays the message now you've gone too far.
Explanation & Answer
We can place strings of text into arrays in java in the same way as for integers.
The initialization is done as follows:
String[] Stringnew=new String[2];
Stringnew[0]="Arrays";
Stringnew[1]="Example";
We create java code in which an array of three strings is initialized and encksed in a try catch block which can handle array out of bounds exception if one arises.
class Arrayofstrings {
public static void main(String args[]) {
try {
// let's make our own array of strings
int num_states=3;
int i;
String[] states = new String[]
{ "California", "Ohio",
"Miami"};
for(i = 0; i < num_states; i++)
{
System.out.println(states[i]);
}
}//try block ends
catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Error:Array Out of Bound;;;You have gone too far");
}
}
}
Output:
California
Ohio
Miami
Review
Review
24/7 Homework Help
Stuck on a homework question? Our verified tutors can answer all questions, from basic math to advanced rocket science!
Similar Content
Related Tags
Into the Wild
by Jon Krakauer
Night
by Elie Wiesel
Extreme Ownership - How US Navy SEALs Lead and Win
by Jocko Willink and Leif Babin
All Quiet on the Western Front
by Erich Maria Remarque
A Separate Peace
by John Knowles
The Dispossessed
by Ursula Kroeber Le Guin
How to Win at the Sport of Business
by Mark Cuban
Frankenstein
by Mary Shelley