Search code examples
javaarraysmethodscomputer-science

Having trouble filling an array of binary numbers from an integer


This is the question we were assigned :

Nine coins are placed in a 3x3 matrix with some face up and some face down. You can represent the state of the coins using a 3x3 matrix with values 0 (heads) and 1 (tails). Here are some examples:

0 0 0 1 0 1 1 1 0 0 1 0 0 0 1 1 0 0 0 0 0 1 0 0 0 0 1

Each state can also be represented using a binary number. For example, the preceding matrices correspond to the numbers:

000010000 101001100 110100001

There are a total of 512 possibilities, so you can use decimal numbers 0, 1, 2, 3,...,511 to represent all the states of the matrix.

Write a program that prompts the user to enter a number between 0 and 511 and displays the corresponding matrix with the characters H and T.

I want the method toBinary() to fill the array binaryNumbers. I realized that this does not fill in 0s to the left. I have to think that through but is that the only thing that is the problem?

//https://www.geeksforgeeks.org/java-program-for-decimal-to-binary-conversion/ 
import java.util.Scanner; 
public class HeadsAndTails {

public static void main(String[] args) {

    Scanner input = new Scanner(System.in); 
    int num = input.nextInt(); 
    int[] binaryNumbers = toBinary(num);

    for (int i = 0; i < 9; i++) {

    printArr(binaryNumbers); 
    System.out.print(binaryNumbers[1]); 
}
}

public static int[] toBinary(int inputtedNumber) { 

    int[] binaryNum = new int[9]; 
    int i = 0; 

    while (inputtedNumber > 0) { 

        binaryNum[i] = inputtedNumber % 2; 
        inputtedNumber = inputtedNumber/2; 
        inputtedNumber++; 

    } return binaryNum; 

} 
public static void printArr(int[] arr) { 

    for (int i = 0; i < 9; i++) {

        if (arr[i] == 0) { 

            System.out.print("H "); 

        } else { 

            System.out.print("T "); 

        }

        if (arr[i+1] % 3 == 0) {

            System.out.println(); 

        } System.out.print(arr[i]);

    } 

}
}

Solution

  • Looks like you are incrementing the wrong variable in your while loop:

    while (inputtedNumber > 0) { 
    
        binaryNum[i] = inputtedNumber % 2; 
        inputtedNumber = inputtedNumber/2; 
        i++; // NOT inputtedNumber
    
    } return binaryNum;
    

    Also note, a new int[9] is probably already initialized to 0, but if not, you could just loop 9 times, rather than until the inputtedNumber is 0:

    for (int i = 0; i < 9; i++) { 
        binaryNum[i] = inputtedNumber % 2; 
        inputtedNumber = inputtedNumber/2; 
    } 
    return binaryNum;
    

    Finally, I think your array might be backwards when you're done, so you may need to reverse it or output it in reverse order