Click here to Skip to main content
15,881,938 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
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 once I get 000000011 perhaps, I want to print a matrix that looks like:

HHH
HHH
HTT

Anyone have an idea? Here is my code so far, however my method is empty.

Java
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(" ");
    }

}


What I have tried:

I've tried using Charachter.isDigit but that didnt seem to be very useful. I was also told there was a binaryToString convertor but I couldnt find that.
Posted
Updated 21-Feb-18 8:04am
Comments
Dr.Walt Fair, PE 21-Feb-18 12:13pm    
Are you restricted to integers? Howmany bytes?
Member 13689295 21-Feb-18 12:44pm    
Yes user can only enter between 1-511. Not sure what you mean about bytes.

1 solution

There is an inbuilt method in java Integer.toString(int i,int radix) which converts integer into binary and returns the binary value as a string which you can store in a strin g variable .

Integer.toString(int i,int radix)

i − This is an integer to be converted.

radix − This is the radix to use in the string representation.


In your programme , you can directly write

String binaryValue = Integer.toString(number,2);

2 is the radix of binary number system
8 for octal
16 for hexadecimal
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900