2013-04-24 141 views
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); 

    } 
} 
+0

System.getProperty(「line.separator」); – 2013-04-24 17:20:01

+0

看看這裏http://stackoverflow.com/questions/7696347/to-break-a-message-in-two-or-more-lines-in-joptionpane – 2013-04-24 17:20:38

回答

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