0

好的,这是我的程序,它可以工作,但我无法让二进制文件进入下一行。相反,它会变长并离开屏幕。

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);

    }
}
4

1 回答 1

0

您已经创建了一组 8 个二进制数字来构成一个字节。只需为要在一行上显示的字节数添加一个计数器。

我选择了 4 来编写这个示例。

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);
    }
}
于 2013-04-24T17:32:54.307 回答