FYI: This is a practice homework exercise. I've been working on it, but now I'm stuck. Any tips/help would be appreciated. I've been staring at it a while and no progress has been made.
Summarized question: Nine coins are place in a 3x3 matrix with some face up and some face down. Heads = 0 and tails = 1. Each state can also be represented using a binary number. There are 512 possibilities. Problem: Write a program that asks user for a number between 0-511 and displays corresponding matrix with characters H and T like this:
User enters number 7 (which is 000000111 or HHHHHHTTT) Display should be: H H H H H H T T T
This is what I have so far. I'm not asking for the answer necessarily, I would just like a push in the right direction. Thanks
import java.util.Scanner;
public class converting {
public static void main(String[] ar) {
Scanner s = new Scanner(System.in);
System.out.print("Enter a number between 0 and 511: ");
int number = s.nextInt();
if(number <= 511 && number > 0)
{
String bin = Integer.toBinaryString(number);
String tails = bin.replace('1', 'T');
int count = 0;
char[] arr = tails.toCharArray();
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i]);
count++;
if (count == 3) {
System.out.println();
count = 0;
}
}
}
else{
System.out.print("Please enter a number between 0 and 511\n");
}
}
}