Hey guys,

Here's my problem:

I developed some code that converts binary to characters and characters to binary. At first all went well (by first I mean on the good ol' console), but when i tried implementing a GUI, some weird stuff came up.

When I try converting characters (strings to be more exact), the output for the binary goes swell, but when I try doing the opposite, it either catches an Exception or it erases the text from the Binary JTextArea and leaves nothing on the Text JTextArea (Text is the TextArea ASCII characters are supposed to be written on).

Since the code is pretty long and (probably) very buggy, I'm uploading the entire code as an attachment.

I have a vague idea of where the problem is:

if(!focusBool) {
                    inputBinary = binArea.getText();
                    binArea.setText(inputBinary);
                    try {
                        outputBinary = Bin2String(inputBinary);
                    }
                    catch(Exception exc) {
                        JOptionPane.showMessageDialog(null, 
                                errorMessage, "Invalid Data", 
                                JOptionPane.ERROR_MESSAGE);
                    }
                    textArea.setText(outputBinary);
                }
                else {
                    inputString = textArea.getText();
                    textArea.setText(inputString);
                    try {
                        outputString = String2Bin(inputString);
                    }
                    catch(Exception exc) {
                        JOptionPane.showMessageDialog(null, 
                                errorMessage, "Invalid Data", 
                                JOptionPane.ERROR_MESSAGE);
                    }
                    binArea.setText(outputString);
                }
            }

Not sure though. Could be a problem in the actual conversion.

Another interesting thing I thought would be worth mentioning. When I debug the Binary JTextArea with small binary numbers, such as "01010100", it actually returns "T", but the same doesn't apply when trying "01010100"(x11). Overflow, maybe?

I would recommend actually compiling my code, since there are plenty of bugs that I could have a hand with.

All help is very welcome.

Thank you in advance,
~Renato

P.S.: Using NetBeans 7.0 and on Vista.

Attachments
package binaryconversion;

import java.util.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class Main
        extends JFrame
{

    private String outputBinary;
    private String outputString;
    private String inputBinary;
    private String inputString;
    private String errorMessage = "Invalid Data Input Value. Please Try Again.";

    private static String String2Bin(String s) throws Exception {
        byte[] bytes;
        String result;
        StringBuffer binary = new StringBuffer();
        //Scanner sc = new Scanner(System.in);

            //s = sc.nextLine();
            bytes = s.getBytes();
        
            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(' ');
            }
        result = binary.toString();    
            
        return result;
    }

    private static String Bin2String(String bin) throws Exception {
        int base = 2;
        //Scanner sc = new Scanner(System.in);
        String aux, foo = "", str = "";
        char c;
        int i=0, l, j=0;

        //bin = sc.nextLine();

        aux = bin.trim();
        l = aux.length();
        l = l/8;

        do {
            foo = aux.substring(i+j, i+(j+8));

            int decimal = Integer.parseInt(foo, base);
            c = (char) decimal;
            str += c;
            j++;
            i+=8;
        }while(i<l*8);

        return str;
    }
    
    private String initTextMsg = "Type your text here!";
    private String initBinMsg = "";
    boolean focusBool;

    public static void main (String[] args){        
        new Main();
    }
    private JButton translateButton;
    private JButton textClearButton, binClearButton;
    private JTextArea textArea, binArea;
    private JScrollPane textScroll, binScroll;
    public Main() {
        ButtonListener bl   = new ButtonListener();
        windowEvent we      = new windowEvent();
        mainPanel panel    = new mainPanel();
        focusListener fl = new focusListener();
        
        translateButton = new JButton("Translate");
        translateButton.addActionListener(bl);
        
        textClearButton = new JButton("Clear Text");
        binClearButton = new JButton("Clear Binary");
        textClearButton.addActionListener(bl);
        binClearButton.addActionListener(bl);
        
        textArea = new JTextArea(initTextMsg, 20, 25);
        binArea  = new JTextArea(initBinMsg, 20, 25);
        
        textArea.setWrapStyleWord(true);
        textArea.setLineWrap(true);
        textArea.setToolTipText("Retrieves or displays the ASCII "
                + "text to be translated from or to binary.");
        binArea.setToolTipText("Retrieves or displays the binary "
                + "to be translated from or to ASCII text");
        binArea.setWrapStyleWord(true);
        binArea.setLineWrap(true);
        
        //textArea.requestFocus();
        textArea.addFocusListener(fl);
        binArea.addFocusListener(fl);
        
        textScroll = new JScrollPane(textArea, 
                JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
                JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
        binScroll  = new JScrollPane(binArea,
                JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
                JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
        
        panel.add(textScroll);
        panel.add(translateButton);
        panel.add(binScroll);
        panel.add(textClearButton);
        panel.add(binClearButton);
        panel.setVisible(true);
        this.add(panel);
        
        this.setSize(800, 600);
        this.setDefaultCloseOperation(
                JFrame.EXIT_ON_CLOSE);
        this.addWindowListener(we);
        this.setTitle("Translator");
        this.setLocationRelativeTo(null);
        this.setVisible(true);
    }
    private class mainPanel extends JPanel {
        public void mainPanel() {
        
        }
    }
    private class ButtonListener implements ActionListener {       
        public void actionPerformed(ActionEvent e) {
            if(e.getSource() == translateButton) {
                if(!focusBool) {
                    inputBinary = binArea.getText();
                    binArea.setText(inputBinary);
                    try {
                        outputBinary = Bin2String(inputBinary);
                    }
                    catch(Exception exc) {
                        JOptionPane.showMessageDialog(null, 
                                errorMessage, "Invalid Data", 
                                JOptionPane.ERROR_MESSAGE);
                    }
                    textArea.setText(outputBinary);
                }
                else {
                    inputString = textArea.getText();
                    textArea.setText(inputString);
                    try {
                        outputString = String2Bin(inputString);
                    }
                    catch(Exception exc) {
                        JOptionPane.showMessageDialog(null, 
                                errorMessage, "Invalid Data", 
                                JOptionPane.ERROR_MESSAGE);
                    }
                    binArea.setText(outputString);
                }
            }
            if(e.getSource() == textClearButton) {
                textArea.setText("");
            }
            if(e.getSource() == binClearButton) {
                binArea.setText("");
            }
        }
    }
    private class windowEvent extends WindowAdapter {
        public void windowClosing(WindowEvent e) {
            
        }
    }
    private class focusListener extends FocusAdapter {
        public void focusGained(FocusEvent fe) {
                if(fe.getSource() == textArea) {
                    focusBool = true;
                }
                if(fe.getSource() == binArea) {
                    focusBool = false;
                }
        }
    }

}

//Put this on main after you're done...
/*try {
            outputBinary = String2Bin();
                System.out.println(outputBinary);
            outputString = Bin2String();
                System.out.println(outputString);
        }

        catch(Exception e) {
            JOptionPane.showMessageDialog(null, errorMessage, "Invalid Data", JOptionPane.ERROR_MESSAGE);
        }*/

One thing I see in your posted code is that you fall thru to set the textfield out of the catch phrase. Why not have the setText() call before the catch?
Also the error message does NOT show what the invalid data is.

Another suggestion is to do a printStackTrace to show what the actual error is.

Edited 5 Years Ago by NormR1: n/a

Well... For your "T" problem...
"01010100" is binary for decimal 84, which is the ASCII code for "T",
so it looks like some implicit conversion is taking place.
a) Make sure that outputString is actually a string variable,
b) Make sure that your String2Bin function actually returns a string.

Am I right in thinking that you convert 1 char to a NINE char String (8 1/0s and a blank), but try to parse them back as 8 binary chars / char.

Catching an exception and throwing away the exception message is just dumb. At the very least print it and its stack to System.err so you have some idea of what went wrong and where.

First of all, thanks for replying. Now:

@NormR1

One thing I see in your posted code is that you fall thru to set the textfield out of the catch phrase. Why not have the setText() call before the catch?

Tried inserting the setText() inside the try block, but still not working.

@hfx642

a) Make sure that outputString is actually a string variable,

Check!

b) Make sure that your String2Bin function actually returns a string.

Check!

@JamesCherrill

Am I right in thinking that you convert 1 char to a NINE char String (8 1/0s and a blank), but try to parse them back as 8 binary chars / char.

It actually trim() the String the binary sequence is in. If my assumptions are correct, trim() actually returns the same String but with no blank spaces. That way I can divide it by 8 and get each binary sequence inputted.

Catching an exception and throwing away the exception message is just dumb. At the very least print it and its stack to System.err so you have some idea of what went wrong and where.

Done.

Attached the new version but still bugged .java file.

Once again, thanks for replying,

~Renato

Edited 5 Years Ago by CrazyPixel: n/a

Attachments
package binaryconversion;

import java.util.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;

public class Main
        extends JFrame
{

    private String outputBinary;
    private String outputString;
    private String inputBinary;
    private String inputString;
    private String errorMessage;

    private static String String2Bin(String s) throws Exception {
        byte[] bytes;
        String result;
        StringBuffer binary = new StringBuffer();
        //Scanner sc = new Scanner(System.in);

            //s = sc.nextLine();
            bytes = s.getBytes();
        
            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(' ');
            }
        result = binary.toString();    
            
        return result;
    }

    private static String Bin2String(String bin) throws Exception {
        int base = 2;
        //Scanner sc = new Scanner(System.in);
        String aux, foo = "", str = "";
        char c;
        int i=0, l, j=0;

        //bin = sc.nextLine();

        aux = bin.trim();
        l = aux.length();
        l = l/8;

        do {
            foo = aux.substring(i+j, i+(j+8));

            int decimal = Integer.parseInt(foo, base);
            c = (char) decimal;
            str += c;
            j++;
            i+=8;
        }while(i<l*8);

        return str;
    }
    
    private String initTextMsg = "Type your text here!";
    private String initBinMsg = "";
    boolean focusBool;

    public static void main (String[] args){        
        new Main();
    }
    private JButton translateButton;
    private JButton textClearButton, binClearButton;
    private JTextArea textArea, binArea;
    private JScrollPane textScroll, binScroll;
    public Main() {
        ButtonListener bl   = new ButtonListener();
        windowEvent we      = new windowEvent();
        mainPanel panel    = new mainPanel();
        focusListener fl = new focusListener();
        
        translateButton = new JButton("Translate");
        translateButton.addActionListener(bl);
        
        textClearButton = new JButton("Clear Text");
        binClearButton = new JButton("Clear Binary");
        textClearButton.addActionListener(bl);
        binClearButton.addActionListener(bl);
        
        textArea = new JTextArea(initTextMsg, 20, 25);
        binArea  = new JTextArea(initBinMsg, 20, 25);
        
        textArea.setWrapStyleWord(true);
        textArea.setLineWrap(true);
        textArea.setToolTipText("Retrieves or displays the ASCII "
                + "text to be translated from or to binary.");
        binArea.setToolTipText("Retrieves or displays the binary "
                + "to be translated from or to ASCII text");
        binArea.setWrapStyleWord(true);
        binArea.setLineWrap(true);
        
        //textArea.requestFocus();
        textArea.addFocusListener(fl);
        binArea.addFocusListener(fl);
        
        textScroll = new JScrollPane(textArea, 
                JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
                JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
        binScroll  = new JScrollPane(binArea,
                JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
                JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
        
        panel.add(textScroll);
        panel.add(translateButton);
        panel.add(binScroll);
        panel.add(textClearButton);
        panel.add(binClearButton);
        panel.setVisible(true);
        this.add(panel);
        
        this.setSize(800, 600);
        this.setDefaultCloseOperation(
                JFrame.EXIT_ON_CLOSE);
        this.addWindowListener(we);
        this.setTitle("Translator");
        this.setLocationRelativeTo(null);
        this.setVisible(true);
    }
    public static String getStackTrace(Throwable t)
    {
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw, true);
        t.printStackTrace(pw);
        pw.flush();
        sw.flush();
        return sw.toString();
    }
    private class mainPanel extends JPanel {
        public void mainPanel() {
        
        }
    }
    private class ButtonListener implements ActionListener {       
        public void actionPerformed(ActionEvent e) {
            if(e.getSource() == translateButton) {
                if(!focusBool) {
                    inputBinary = binArea.getText();
                    binArea.setText(inputBinary);
                    try {
                        outputBinary = Bin2String(inputBinary);
                        textArea.setText(outputBinary);
                    }
                    catch(Exception exc) {
                        errorMessage = getStackTrace(exc);
                        JOptionPane.showMessageDialog(null, 
                                errorMessage, "Exception caught!", 
                                JOptionPane.ERROR_MESSAGE);
                    }
                }
                else {
                    inputString = textArea.getText();
                    textArea.setText(inputString);
                    try {
                        outputString = String2Bin(inputString);
                        binArea.setText(outputString);
                    }
                    catch(Exception exc) {
                        errorMessage = getStackTrace(exc);
                        JOptionPane.showMessageDialog(null, 
                                errorMessage, "Exception caught!", 
                                JOptionPane.ERROR_MESSAGE);
                    }
                }
            }
            if(e.getSource() == textClearButton) {
                textArea.setText("");
            }
            if(e.getSource() == binClearButton) {
                binArea.setText("");
            }
        }
    }
    private class windowEvent extends WindowAdapter {
        public void windowClosing(WindowEvent e) {
            
        }
    }
    private class focusListener extends FocusAdapter {
        public void focusGained(FocusEvent fe) {
                if(fe.getSource() == textArea) {
                    focusBool = true;
                }
                if(fe.getSource() == binArea) {
                    focusBool = false;
                }
        }
    }

}

//Put this on main after you're done...
/*try {
            outputBinary = String2Bin();
                System.out.println(outputBinary);
            outputString = Bin2String();
                System.out.println(outputString);
        }

        catch(Exception e) {
            JOptionPane.showMessageDialog(null, errorMessage, "Invalid Data", JOptionPane.ERROR_MESSAGE);
        }*/

It actually trim() the String the binary sequence is in. If my assumptions are correct, trim() actually returns the same String but with no blank spaces. That way I can divide it by 8 and get each binary sequence inputted.

Not quite - llike the API doc says "Returns a copy of the string, with leading and trailing whitespace omitted." ie it does not remove embedded blanks

Sometimes this happens:

it erases the text from the Binary JTextArea and leaves nothing on the Text JTextArea

And sometimes it outputs the error I attached (had to screen cap it - too long).

EDIT:

Not quite - llike the API doc says "Returns a copy of the string, with leading and trailing whitespace omitted." ie it does not remove embedded blanks

So I would have to replace all of the blank spaces instead of using trim() ?

Edited 5 Years Ago by CrazyPixel: n/a

Attachments errorOutput.PNG 38.55 KB

Your attached console image shows that you have an indexing problem at line 56.

Can you explain how the Bin2String method is supposed to work? The logic appears to require that the string it is parsing be a multiple of 8 characters long. Perhaps your code should prepend some 0s to make the string the correct length. For example if the input is 111 the add 5 0s to make 00000111.

Edited 5 Years Ago by NormR1: n/a

Perhaps your code should prepend some 0s to make the string the correct length. For example if the input is 111 the add 5 0s to make 00000111.

I suppose the user knows binary sequences are supposed to be 8 characters long. But I'll implement that too. Thanks for the advice.

So I would have to replace all of the blank spaces instead of using trim() ?

Yes, OR, leave the String exactly as it was created and loop in blocks of 9 (just processing the first 8 chars of each). When you have this kind of encode/decode pair it's always a good idea to try to make the two methods as near as possible to exact mirror images of each other - that maximises the chances of them working together properly.

@JamesCherrill

Alright, I've replaced bin = aux.trim(); to aux = bin.replaceAll("/s", ""); It doesn't seem to have changed anything. It still outputs the same exception or clears the textArea when trying to translate bin. seq. to ASCII characters.

Why don't you look at your code and see what the logic is that creates the exception or clears the TextArea.

The one exception you posted was because the code did NOT make sure the string length was a multiple of 8. You must change the code to prevent that.
What exception are you now getting? Copy and paste the full text of the error message here.
Where in your code is the textArea cleared? What in the program logic allows that to happen?

String out of bounds... I'll take a look at it later.

@NormR1 I didn't code anything that would allow textArea to be cleared without pushing the Clear Text Button.

Thanks to everyone who helped me out. You guys are awesome.

Here is the complete exception list (see attached file).

And here's the input: 01001000 01100101 01101100 01101100 01101111 00100000 01001000 01100101 01101100 01101100 01101111 P.S.: Interestingly, when I typed "01001000 01100101 01101100 01101100 01101111", it actually printed "Hello", when I doubled that "Hello" in binary, it threw me an exception. That's obviously related to StringOutOfBoundsException .

Edited 5 Years Ago by CrazyPixel: n/a

Attachments errorOutput.PNG 38.49 KB
This article has been dead for over six months. Start a new discussion instead.