tags:

views:

74

answers:

3

Hey SO

for (int i = TrueProbDie; i < 100; i++) {
  assert(i>=0);
  probs[i] = 1;
}

Im getting an ArrayIndexOutOfBoundsException on this code, due to i becoming negative, this I can solve by editing my other code, what getting me is that its ever making it to the

probs[i] = 1;

line as should throw an error on

assert(i>=0);

, if im writing this correctly , im relatively new to asserts, so im assuming I am making a newbie mistake of some kind, i just cant track it down.

many thanks ^_^

A: 

Are you certain that i is negative? If probs contains fewer than 100 elements, you'll get that exception for trying to read past the end.

Skirwan
the line above it is int[] probs = new int[100];and my exact exception isException in thread "main" java.lang.ArrayIndexOutOfBoundsException: -29 at Genetics.Population.ProbablityArrayDeath(Population.java:93) at Genetics.Population.kill(Population.java:186) at Genetics.Population.run(Population.java:49) at Control.Main.main(Main.java:38)Thanks
Gwilym
+2  A: 

Assertions are disabled by default in Java.

Re-run this code with java -enableassertions and the assertion will actually be checked and you'll get an AssertionError before you get to the point where you're assigning a value at index -1.

gab
thanks to you aswell
Gwilym
+3  A: 

http://java.sun.com/j2se/1.4.2/docs/guide/lang/assert.html#enable-disable

"By default, assertions are disabled at runtime. Two command-line switches allow you to selectively enable or disable assertions.

To enable assertions at various granularities, use the -enableassertions, or -ea, switch. To disable assertions at various granularities, use the -disableassertions, or -da, switch. You specify the granularity with the arguments that you provide to the switch:"

mlaw
Ah it all makes sence now, thank you
Gwilym