FAQ - james-bern/CS136 GitHub Wiki
FAQ
ArrayIndexOutOfBoundsException
Background
- An array has a fixed number of slots; the number of slot's is the arrays' length.
- In Java, arrays are zero-indexed; this means we start indexing the array at
0.
Explanation
- An index must satisfy the array's bounds $0 \leq i \leq (\texttt{array.length - 1})$.
- We can also write the bounds as $0 \leq i < \texttt{array.length}$.
- An index that does not satisfy the bounds is "out of bounds."
Example
xxxxxx xxxxxx xxxxxx xxxxxx xxxxxx
foo[0] foo[1] foo[2] foo[3] foo[4]
int[] foo = new int[5]; has length 5.
- We can index into the array with
foo[0], foo[1], foo[2], foo[3], and foo[4].
- The only valid indexes into
foo are 0, 1, 2, 3, and 4.
foo[5] will throw an ArrayIndexOutOfBoundsException.
foo[42] will throw an ArrayIndexOutOfBoundsException.
foo[-1] will throw an ArrayIndexOutOfBoundsException.
How can I add sound?
import javax.sound.sampled.*;
//https://stackoverflow.com/questions/3780406/how-to-play-a-sound-alert-in-a-java-application
static class SoundUtils {
public static float SAMPLE_RATE = 8000f;
public static void init() {
if (sdl != null) {
sdl.drain();
sdl.stop();
sdl.close();
}
try {
AudioFormat af =
new AudioFormat(
SAMPLE_RATE, // sampleRate
8, // sampleSizeInBits
1, // channels
true, // signed
false); // bigEndian
sdl = AudioSystem.getSourceDataLine(af);
sdl.open(af);
sdl.start();
} catch (Exception e) {}
}
public static void tone(int hz, int msecs) {
tone(hz, msecs, 1.0);
}
static SourceDataLine sdl;
public static void tone(int hz, int msecs, double vol) {
byte[] buf = new byte[1];
for (int i = 0; i < 8 * msecs; i++) {
double angle = i / (SAMPLE_RATE / hz) * 2.0 * Math.PI;
buf[0] = (byte)(Math.sin(angle) * 127.0 * vol);
sdl.write(buf,0,1);
}
}
}