Reputation: 3
So I'm writing this program that simulates a coinflip with sides H and T, and its come time to create my method. The main idea behind the program is that a user should be able to enter any number b/w 1 and 511. Once the number is entered, my method should convert their number to binary, 0's being Heads, and 1's being Tails.
So if the user enters, 3, my methos should convert to 000000011, and then I want to convert it to print a matrix that looks like:
HHH
HHH
HTT
Here is my code so far, however my method (binaryConverter) is empty.I really have no clue where to begin.
import java.util.Scanner;
public class Problem8_11 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter one number between 0 and 511: ");
int number = input.nextInt();
String binaryValue = binaryConverter(number);
int[][] matrix = new int[3][3];
int binary = 0;
for (int i = 0; i < matrix.length; i++) {
for (int x = 0; x < matrix[i].length; x++) {
int HeadOrTails = (binaryValue.charAt(binary++) == '0') ? 0 : 1;
matrix[x][i] = HeadOrTails;
}
}
for (int i = 0; i < matrix.length; i++) {
for (int x = 0; x < matrix[i].length; x++) {
char HorT = (matrix[i][x] == 0) ? 'H' : 'T';
System.out.print(HorT + "");
}
System.out.println(" ");
}
}
Upvotes: 0
Views: 92
Reputation: 683
If your problem is just on how to convert an int to a binary string, that is already answered in below question: Converting an int to a binary string representation in Java?
You need to append any leading zeros of course. So your binary converter can do something like below:
String convertToBinaryString(int i){
String bString = Integer.toBinaryString(i);
while(bString.length() < 12){
bString = "0" + bString;
}
return bString ;
}
Upvotes: 0
Reputation: 65849
You don't need to convert to string - that is wasteful.
Use simple bit testing.
private boolean test(int n, int bit) {
return ((1 << bit) & n) != 0;
}
private String test(int n, int bit, String t, String f) {
return test(n, bit) ? t : f;
}
public void test(String[] args) {
int n = 3;
for (int bit = 8; bit >= 0; bit--) {
System.out.print(test(n, bit, "H", "T"));
}
}
TTTTTTTHH
Upvotes: 1