0

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

5
  • If number = 5, number/2 returns 2 and hence modNumber is never equals to 0. Commented Nov 3, 2013 at 17:33
  • BTW, you may want to use bit masks and shift operators instead of mod and division. Will be way faster and cleaner. Commented Nov 3, 2013 at 17:35
  • Thanks for the reply, I've never heard of those so I'll have a look. They sound like something to do with cryptography? Commented Nov 3, 2013 at 17:47
  • and Thank you ZouZou too Commented Nov 3, 2013 at 17:48
  • Does this answer your question? ArrayList index out of bounds Commented Oct 3, 2022 at 4:22

1 Answer 1

4

You never change number in your loop, and you assign modNumber = number / 2 in the loop, so from the second iteration onward modNumber is a constant (for most of the first iteration it's 2, but then you assign number / 2 to it); if you reach that point at all, you'll stay there. So the loop continues until counter reaches 30, at which point digits[counter] throws the exception.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! You can imagine my inward groan when I realised that I completely missed that

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.