# How to: Select specific array indices?

• 03-07-2011, 10:36 PM
louist
How to: Select specific array indices?
Hello! I'm new to these forums, Java, and programming in general, and I could use some help.

For an assignment I need to write a program that converts a decimal number into the equivalent binary, octal, and hexadecimal numbers. I can convert them just fine, but the assignment requires that I format the binary output with a dash between each set of 4 bits (like so: 1011-1101-0001-0101), which I'm having trouble with.

What I'm trying to do, below, is convert the decimal number into an array of binary numbers (which is working), and use a for-each loop to print the array and a selector to insert the dashes (which is not working):

Code:

```public class tester {     public static void main(String[] args) {           int decimal = 1000;         int[] bin = new int[16];               convert(decimal, 2, bin);                         System.out.println("Dec: " + decimal);         System.out.print("Bin: ");                 for (int u: bin) {             if (bin[u] % 4 == 0) {                 System.out.print(u + "-");             }             else {                 System.out.print(u);             }         }     }         public static void convert(int dec, int base, int[] array) {               for (int i = (array.length - 1); i >= 0; i--) {             array[i] = dec % base;             dec /= base;         }     } }```

What I was hoping to receive was:
Code:

```Dec: 1000 Bin: 0000-0011-1110-1000```

And what I got was:
Code:

```Dec: 1000 Bin: 0-0-0-0-0-0-111110-10-0-0-```

I see what the problem is: Java is testing the element instead of the index itself. Is it possible to check the index itself?

::Edit:: I think, now, that I have figured a way to do this using a regular for loop, but I'm still curious if/how you can select specific indexes.

::Edit Two:: For anyone who might be interested, here is a for loop in which I get the proper output:
Code:

```for (int i = 0; i < bin.length; i++) {             if ((i + 1) % 4 == 0  && i != 15) {                 System.out.print(bin[i] + "-");             }             else {                 System.out.print(bin[i]);             }         }```
• 03-07-2011, 11:04 PM
sunde887
The problem is the for each loop, which you figured out, it just continues as long as the list has more items. You could use indexOf but since you have all ones and zeroes you would get a wrong answer. It looks like for this solution the for:each loop is a bad approach.
• 03-07-2011, 11:18 PM
louist
Thank you for the response.

Are there ever cases where you might do something more complex with a for-each loop than just run through every element?
• 03-07-2011, 11:21 PM
sunde887
I am not experienced enough to give you a truly solid answer. Try in your original for each loop adding a print line to print the indexOf the item and see what it prints. It may allow you to determine where the item is stored