I am writing a program to print out a user inputed integer into binary form. When I run it and input, say the number 5, it crashes and gives me the error:
java.lang.ArrayIndexOutOfBoundsException: 30 at PrintBinaryDigitsFixed.main(PrintBinaryDigitsFixed.java:27) i.e the line "digits[counter] = number % 2;"
Why am I getting an out of bounds exception? It should assign the remainder to the first element then move on to the second shouldn't it?
I feel like I'm making a glaringly obvious mistake but I can't tell what it is
final int MIN = 0; final int MAX = (int) (Math.pow(2, 30) - 1); int[] digits = new int[30]; //array to hold the digits int number = readInput ("Enter an integer from " + MIN + " to " + MAX, MIN, MAX); int counter = 0; int modNumber = 2; while(modNumber / 2 != 0) { digits[counter] = number % 2; modNumber = number / 2; counter++; } System.out.print(number + " in binary form is "); listBackwardsFrom(digits, counter); Thanks
number = 5,number/2returns2and hencemodNumberis never equals to 0.