Question: Please help with java code!!! Must include functionality to convert a binary number over to a decimal number. This can be accomplished by using a
Please help with java code!!!
Must include functionality to convert a binary number over to a decimal number. This can be accomplished by using a second convert button, and redoing your actionPerformed() method.
must convert both from BASE2 to BASE10 and BASE10 to BASE2 and handle errors for both. Use popups to display error conditions. After the user responds to the popup, clear the bad data and position the curser for new input. Define and throw your own NotInBinaryFormatException to handle the BASE2 -> BASE10. Use NumberFormatException to handle BASE10 -> BASE2. Be sure your error messages appear on the same monitor and over the converter application
import javax.swing.JTextField;
import javax.swing.JLabel;
import javax.swing.JFrame;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.FlowLayout;
public class BinaryCalculator extends JFrame implements ActionListener
{
private JButton clearButton;
private JButton convertButton;
private JTextField output;
private JTextField input;
public BinaryCalculator ()
{
super("Binary and Decimal Calculator");
setLayout(new FlowLayout());
setSize(350,200);
input = new JTextField(30);
output = new JTextField(30);
convertButton = new JButton("Convert");
clearButton = new JButton ("Clear");
convertButton.addActionListener(this);
clearButton.addActionListener(this);
convertButton.setActionCommand("convert");
clearButton.setActionCommand("clear");
this.add(new JLabel("Decimal"));
this.add(input);
this.add(new JLabel("Binary"));
this.add(output);
this.add(convertButton);
this.add(clearButton);
}
private String convertToBinary(String numString)
{
int num = Integer.parseInt(numString);
if (num == 0)
return "";
else if (num % 2 == 1)
return convertToBinary(Integer.toString(num/2)) + "1";
else
return convertToBinary(Integer.toString(num/2)) + "0";
}
public void actionPerformed(ActionEvent e)
{
String s = e.getActionCommand();
if (s.contentEquals("convert"))
{
String aNumber = input.getText();
output.setText(convertToBinary(aNumber));
}
if (s.equals("clear"))
{
input.setText("");
output.setText("");
}
}
public static void main (String args[])
{
BinaryCalculator b = new BinaryCalculator();
b.setVisible(true);
}
}
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
