NAce01
NAce01

Reputation: 57

How To Print Spaces Between Text Output

The program is simple in concept: I simply need to print a space between every 8 numbers, and there needs to be a space in front of the first digit. It should look something like this: 65536(10) = 1 00000000 00000000. However, I am not sure how to write this code. I tried using the split method, but it didn't work, and now I'm trying this:

String binaryStr = "";
int saveInt, intValue, quotient, remainder;
int cnt = 0;
    
System.out.println ("\n(7) Converting an unsigned Integer to binary.");
System.out.print   ("Enter an integer value: ");
intValue = kb.nextInt();

if (intValue >=  0)
    {
    saveInt = intValue;

    while (intValue > 0)
        {
        remainder = intValue % 2;
        intValue = intValue / 2;
        binaryStr = (char)(remainder+48) + binaryStr;
     for (cnt = binaryStr.length(); cnt < 9; ++cnt) //I tried this to split btwn every 8 spaces. 
     //Not sure how to space after first digit.
        System.out.print(" ");
        }
    System.out.printf ("After Conversion: %d(10) = %s(2).\n", saveInt, binaryStr);
    }

I appreciate any help. Thanks!

Upvotes: 0

Views: 76

Answers (1)

Oleg Cherednik
Oleg Cherednik

Reputation: 18245

public static void main(String... args) {
    Scanner scan = new Scanner(System.in);
    System.out.println("(7) Converting an unsigned Integer to binary.");
    System.out.print("Enter an integer value: ");
    int num = scan.nextInt();
    String binaryStr = convertToBinary(num);
    System.out.printf("After Conversion: %d(10) = %s(2).\n", num, binaryStr);
}

public static String convertToBinary(int num) {
    String str = Integer.toBinaryString(num);
    StringBuilder buf = new StringBuilder(str.length() + 5);

    for (int i = str.length() - 1, j = 0; i >= 0; i--, j++) {
        if (j > 0 && j % 8 == 0)
            buf.append(' ');
        buf.append(str.charAt(i));
    }

    return buf.reverse().toString();
}

Output:

(7) Converting an unsigned Integer to binary.
Enter an integer value: 65536
After Conversion: 65536(10) = 1 00000000 00000000(2).

Upvotes: 1

Related Questions