0

Ok so here is my program and it works but i'm having trouble getting the binary to go to the next line. Instead it gets to long and goes off the screen.

import javax.swing.*;

public class TextToBinary{
public static void main(String[] args) {

    String y;

    JOptionPane.showMessageDialog(null, "Welcome to the Binary Canary.","Binary Canary", JOptionPane.PLAIN_MESSAGE);

    y = JOptionPane.showInputDialog(null,"Write the word to be converted to binary: ","Binary Canary", JOptionPane.PLAIN_MESSAGE);

     String s = y;
      byte[] bytes = s.getBytes();
      StringBuilder binary = new StringBuilder();
      for (byte b : bytes)
      {  
         int val = b;
         for (int i = 0; i < 8; i++)
         {
            binary.append((val & 128) == 0 ? 0 : 1);
            val <<= 1;
         }
         binary.append(' ');
      }

      JOptionPane.showMessageDialog(null, "'" + s + "' to binary: " +"\n" +binary,"Binary Canary", JOptionPane.PLAIN_MESSAGE);

    }
}
oentoro
  • 740
  • 1
  • 11
  • 32
Logan
  • 9
  • 2

1 Answers1

0

You're already creating a group of 8 binary digits to make a byte. Just add a counter for the number of bytes you want to display on a line.

I picked 4 to code this example.

import javax.swing.JOptionPane;

public class TextToBinary {
    public static void main(String[] args) {

        String y;

        JOptionPane.showMessageDialog(null, "Welcome to the Binary Canary.",
                "Binary Canary", JOptionPane.PLAIN_MESSAGE);

        y = JOptionPane.showInputDialog(null,
                "Write the word to be converted to binary: ", "Binary Canary",
                JOptionPane.PLAIN_MESSAGE);

        String s = y;
        byte[] bytes = s.getBytes();
        StringBuilder binary = new StringBuilder();
        int byteCount = 0;
        for (byte b : bytes) {
            int val = b;
            for (int i = 0; i < 8; i++) {
                binary.append((val & 128) == 0 ? 0 : 1);
                val <<= 1;
            }
            binary.append(' ');
            byteCount++;
            if (byteCount >= 4) {
                binary.append("\n");
                byteCount = 0;
            }
        }

        JOptionPane.showMessageDialog(null, "'" + s + "' to binary: " + "\n"
                + binary, "Binary Canary", JOptionPane.PLAIN_MESSAGE);

        System.exit(0);
    }
}
Gilbert Le Blanc
  • 50,182
  • 6
  • 67
  • 111