Printing out numbers from an Array.
Hi i have the following little programme which prints out some numbers from an Array i declared at the start which holds 5 values. Once the 5 values are printed the programme catches the exception and prints out the message, as there are no more numbers to print!.
Here is the code.
Code :
package ClientServer;
public class GoTooFar {
public static void main(String[] args) {
int dan[] = {26, 42, 55, 67, 43};
try {
for (int counter = 0; counter <= dan.length; counter++) {
System.out.println(dan[counter]);
}
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Youve gone too far");
}
}
}
As you can see the numbers seem to printed out all at the same time, (although scientifically i guess there is a fraction of a second between each one).
My question is how can i make there be 1 second in between printing out each digit?
Re: Printing out numbers from an Array.
Use Thread.Sleep(1000). Incidentally, you'll need to catch the InterruptedException which could be thrown by this method.
It's a bit worrying that you're using the exception to terminate the loop, though... I'd get rid of it and change your conditional to use a less than rather than less than or equal to (unless there's some other reason such as your class requires it).
Re: Printing out numbers from an Array.
Hi,
I have done as you advised with removing the exception handler and just changed the condition to less than.
Regarding the Thread and sleep part, can i do this in the same class or is a new one needed.?
Re: Printing out numbers from an Array.
You can do it in the same class.
and as for the InterruptedException, you can just throw it when you start your "main" method.
Thread.sleep(# of milliseconds); (just in case you want to change the time in between)
For example:
Code :
public static void main(String[] args) throws InterruptedException
{
for (int i = 0; i < 5; i++)
{
System.out.println(i);
Thread.sleep(1000); //sleeps for 1 second
}
}
Re: Printing out numbers from an Array.