0

enter image description here

This code should compile, should it not? What am I doing wrong? I would like the code to briefly pause before displaying each number in the array.

public static void median(int odd[]) throws InterruptedException {

    Arrays.sort(odd);

    for (int i = 0; i < odd.length; i++) {
        System.out.println(odd[i]);
        Thread.sleep(500);
    }
    System.out.println("The median number of the previous list of numbers is: " + odd[5]);
}
Makoto
  • 104,088
  • 27
  • 192
  • 230
Christopher Baldwin
  • 347
  • 2
  • 4
  • 15

4 Answers4

2

I'm assuming that in your main you have something like

public static void main (String[] args) {
    int[] array  = new int[X];
    ...// populate array
    median(array);
}

Because median is a method declared as throwing a checked exception, you must either catch the Exception or rethrow it.

public static void main (String[] args) {
    int[] array  = new int[X];
    ...// populate array
    try {
        median(array);
    } catch (InterruptedException e) {
        // handle it
    }
}

or

public static void main (String[] args) throws InterruptedException {
    int[] array  = new int[X];
    ...// populate array
    median(array);
}
Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
1

It's better to use try catch block for Thread.sleep

Remove the throw exceptions and change

Thread.sleep(500);

to

try{Thread.sleep(500);}catch(Exception e){}
JoeC
  • 1,850
  • 14
  • 12
0

Use Timer or TimerTask instead of making the thread sleep.

iWumbo
  • 135
  • 1
  • 8
0

I'm not entirely convinced that the exception is thrown, but the reason you have to either declare it to be thrown, or catch it yourself, is due to it being a checked exception.

Because InterruptedException is declared as part of the signature of the method, you must address it in some way.

Makoto
  • 104,088
  • 27
  • 192
  • 230