-1

I have this code and in it there is a function to convert binary to decimal. It sets the text of a JTextArea to the result and appends the result to a different JTextArea. The former works fine but the latter causes the above mentioned exception to appear. This is my code below. Pls help.

JButton numerical = new JButton("BIN->NUM");
    numerical.setFont(small);
    numerical.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            Display.setText(String.valueOf(Integer.parseInt(Display.getText(), 2)));
            try {
                Memory.append(String.valueOf(Integer.parseInt(Display.getText(), 2))); 
                Memory.append("\n");
            } catch (Exception ie) {
                Memory.append(String.valueOf(Integer.parseInt(Display.getText(), 2)));
            }
        }
    });
deeznuts
  • 1
  • 2
  • provide the stacktrace please – Nicolas Filotto Jun 02 '16 at 17:27
  • Questions seeking debugging help ("why isn't this code working?") must include the desired behavior, a specific problem or error and the shortest code necessary to reproduce it in the question itself. Questions without a clear problem statement are not useful to other readers. – Jim Garrison Jun 02 '16 at 17:57
  • Possible duplicate of [How to avoid Number Format Exception in java?](http://stackoverflow.com/questions/5499523/how-to-avoid-number-format-exception-in-java) – shoover Jun 02 '16 at 23:12

1 Answers1

3

As you say, the first works fine. At this point

Display.setText(String.valueOf(Integer.parseInt(Display.getText(), 2)));

The input value to parseInt() is in binary form and the conversion works. However the setText() replaces that binary value with the decimal equivalent. Then when you attempt

Memory.append(String.valueOf(Integer.parseInt(Display.getText(), 2))); 

the number is in decimal format and the second conversion fails because you specified base 2 and it expects the number to be in binary.

Jim Garrison
  • 85,615
  • 20
  • 155
  • 190
Henry
  • 42,982
  • 7
  • 68
  • 84