好的,所以这是我的程序,它的工作原理,但我无法让二进制文件转到下一行。相反,它会变长并离开屏幕。
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);
}
}
答案 0 :(得分: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);
}
}