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?
Thank you in advance.
::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]);
}
}