kilzah
kilzah

Reputation: 39

Binary to Decimal Converter GUI JAVA

I've tried to finish my program but it cannot convert to binary what do you think is the problem? if I press convert it would simple run a script saying, string index is out of range on how many digits of the binary. and if so how would I improve the codes. Thank you for the ones who would comment to this thread :>

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

public class BinaryGUI extends BinaryGUIDemo {


        public static void main(String[] args) {
            new BinaryGUI();
        }

        private JFrame frame;
        private JButton button;
        private JTextField text;
        private JTextField text2;
        private String decimalnumber = null;

        public BinaryGUI() {
            frame = new JFrame("Conversion!");

            JLabel label = new JLabel("Binary:");
            frame.setLayout(new FlowLayout());
            frame.add(label);

            text = new JTextField(15);
            frame.add(text);

            JLabel label2 = new JLabel("Decimal:");
            frame.add(label2);

            text2 = new JTextField(15);
            frame.add(text2);

            
            button = new JButton("Convert");
            button.addActionListener(new ButtonListener());
            frame.add(button);
            
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setSize(250, 300);
            frame.setLocationRelativeTo(null);
            frame.setVisible(true);
        }

        public void Convert() {
            String binary = text.getText();
            int i;
            for (i = 0; i < binary.length(); i++) {
                char select = binary.charAt(binary.length() - i);
                char number = (char) (select * Math.pow(2, i));
                decimalnumber += number;
            }
        }

        public class ButtonListener implements ActionListener {
            public void actionPerformed(ActionEvent e) {
                Convert();
                if (button.getText().equals("Convert")) {
                    text2.setText(decimalnumber);
                    text.getText();
                    text2.getText();
                } else {
                }
            }
        }
    }

Upvotes: 0

Views: 535

Answers (2)

kilzah
kilzah

Reputation: 39

CODE FOR CONVERTING
this is what I used in converting binary to decimal. but instead of getting decimal it prints out null+decimal and the maximum binary numbers that it could read is 2 binary number example: Binary:111 when converted to decimal it prints out Null24 which is 11000 in binary that's the problem. When getting big binary numbers 8 digits it explodes and I dont know how to fix this.

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

public class BinaryGUI extends BinaryGUIDemo {


        public static void main(String[] args) {
            new BinaryGUI();
             
            int n;
            String numInput;
            String binary;
            numInput = JOptionPane.showInputDialog(null, "Enter a number:");
            n = Integer.parseInt(numInput);
     
             binary  = Integer.toBinaryString(n);
            JOptionPane.showMessageDialog(null, "Binary equivalent is: " +binary);
        }

        private JFrame frame;
        private JButton button;
        private JTextField text;
        private JTextField text2;
        private String decimalnumber = null;

        public BinaryGUI() {
            
            frame = new JFrame("Conversion!");

            JLabel label = new JLabel("Binary:");
            frame.setLayout(new FlowLayout());
            frame.add(label);

            text = new JTextField(15);
            frame.add(text);

            JLabel label2 = new JLabel("Decimal:");
            frame.add(label2);

            text2 = new JTextField(15);
            frame.add(text2);

            
            button = new JButton("Convert");
            button.addActionListener(new ButtonListener());
            frame.add(button);
            
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setSize(250, 300);
            frame.setLocationRelativeTo(null);
            frame.setVisible(true);
        }

        public void Convert() {
            String binary = text.getText();
            var bits = binary.toCharArray();
            for (int i = 1; i < bits.length; i++) {
                char select = binary.charAt(binary.length() - i - 1);
                if(select == '0') continue;
                int number = 1 << i;
                decimalnumber += number;
            }
        }
        public class ButtonListener implements ActionListener {
            public void actionPerformed(ActionEvent e) {
                Convert();
                if (button.getText().equals("Convert")) {
                    text2.setText(decimalnumber);
                    text.getText();
                    text2.getText();
                } else {
                }
            }
        }
    }

Upvotes: 0

Mushroomator
Mushroomator

Reputation: 9188

There are a couple of issues with your code:

Index ouf of bounds

When using str.charAt() you can only have indices between 0 inclusive and str.length - 1 inclusive, meaning that str.charAt(str.length) will result in an out of bounds error. To prevent that use binary.length() - i - 1 instead of binary.length() - i.

Type-casting to char

What you do in this line char number = (char) (select * Math.pow(2, i)); doesn't make any sense. You want to have an int returned not a char. select is a char here and doesn't hold the value 0 or 1 as you seem to think it does. Also Math.pow() is unnecessary here, you can just use a bit-shift which will be faster and prevent unnecessary type casts.

Ignore 0 bits

As I've pointed out before select hold the chars '0' and '1' which don't translate to 0 and 1 integers as you seem to think. Therefore your calculation with select * Math.pow(2, i) yields unexpected results. Instead you could just use an if condition checking whether a char is '0'. This way you also save an expensive multiplication operation.

As you only index the individual chars of the String you could just transform everything to a char array.

Here an implementation showing how to convert from a binary string to a decimal number. It also shows how you can use Integer::toBinaryString() to convert in the opposite direction.

public class Application {
    public static void main(String[] args) {
        System.out.println(convBinaryStringToInt("1001"));
        System.out.println(convBinaryStringToInt("0001"));
        System.out.println(convBinaryStringToInt("0010"));
        System.out.println(convBinaryStringToInt("0011"));

        // convert the other way round
        System.out.println(Integer.toBinaryString(9));
        System.out.println(Integer.toBinaryString(1));
        System.out.println(Integer.toBinaryString(2));
        System.out.println(Integer.toBinaryString(3));
    }

    public static int convBinaryStringToInt(String binary) {
        int decimalNumber = 0;
        var bits = binary.toCharArray();
        for (int i = 0; i < bits.length; i++) {
            // add -1 otherwise you will run out of bounds
            char bit = bits[bits.length - i - 1];
            // skip zeros
            if(bit == '0') continue;
            // now we know we have a one bit, instead of using Math.pow() we can just bit shift which is faster and
            // prevents unnecessary type casting
            // shift 1 bit to left
            int number = 1 << i;
            decimalNumber += number;
        }
        return decimalNumber;
    }
}

Expected output:

9
1
2
3
1001
1
10
11

Upvotes: 2

Related Questions