Question: I have the code for the following problem, BUT it doesn't work because there can only be spaces inbetween the output of the letters H

I have the code for the following problem, BUT it doesn't work because there can only be spaces inbetween the output of the letters H & T, not before or after. Thank you

---------QUESTION------

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.

------CODE----------------

import java.util.Scanner; public class HeadsAndTails {

public static void main(String[] args) { Scanner sc = new Scanner(System.in);

System.out.print("Enter an integer representing the state of the coins:"); int input = sc.nextInt();

String binary = Integer.toBinaryString(input);

binary = binary.format("%09d", Integer.parseInt(binary));

for (int i = 1; i < 10; i++) { if ('0' == binary.charAt(i - 1)) { System.out.print("H "); } else { System.out.print("T"); }

if (i % 3 == 0) { System.out.println(); } } }

}

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!