When I run the program and it asks me to input a number between 0 to 511. I enter 7 it turns out to be
TTT TTT TTT
but it should be like this HHH HHH TTT
import java.util.Scanner;
public class coins {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter a number between 0 and 511");
int number = input.nextInt();
int[] result = decimalToBinary(number);
displayHeadAndTails(result);
}
public static int[] decimalToBinary(int number) {
int[] result = new int[9];
int i = result.length - 1;
while (number != 0) {
if (number % 2 == 0) {
result[i--] = '0';
} else {
result[i--] = '1';
}
number /= 2;
}
for (int k = i; k >= 0; k--) {
result[k] = '0';
}
return result;
}
public static void displayHeadAndTails(int[] result) {
for (int i = 0; i < 9; i ) {
if (result[i] == 0)
System.out.print("H");
else System.out.print("T");
if ((i 1) % 3 == 0)
System.out.println();
}
}
}
CodePudding user response:
Change result[i] == 0
to result[i] == '0'
and it will work
public static void displayHeadAndTails(int[] result) {
for (int i = 0; i < 9; i ) {
if (result[i] == '0')
System.out.print("H");
else System.out.print("T");
if ((i 1) % 3 == 0)
System.out.println();
}
}
Also,it's better to using {}
after if else
CodePudding user response:
Maybe try using (result[i] = 0) in displayHeadAndTails? as == is used for String comparisons.