Reputation: 679
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");
}
}
}
Upvotes: 1
Views: 1471
Reputation: 11
Upvotes: 1
Reputation: 1075079
You're really close. Some notes:
Scanner#nextInt
can throw exceptions; handle them gracefully.number
is in range (0-511).bin
, you have 1-9 binary digits -- 0
s and 1
s. You want to make sure you have exactly 9 of them, so insert any missing 0
s at the front.0
s and 1
s; you want H
s and T
s. Check out String#replace
.H
s and T
s. Output it in three lines, three chars per line. Check out String#substring
.Upvotes: 4
Reputation: 60013
intToString.toCharArray();
This should be bin.toCharArray()
, methinks.
What else are you having problems with?
Upvotes: 1