鉴于我的转换器程序,如何将二进制输出存储到数组中然后将其输出到屏幕上?目前它只输出转换后的数字,但我需要先将它存储到数组中。我还没有在控制台程序之外实现数组,所以我还不完全确定如何尝试这个。
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.InputMethodListener;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class NumberConverter extends JPanel {
private JLabel binaryLabel = new JLabel();
private JLabel totalone = new JLabel();
private JLabel totaltwo = new JLabel();
private JLabel decimalLabel = new JLabel();
private JTextField hexdecString = new JTextField();
private JButton convert;
public NumberConverter() {
setLayout(new BorderLayout());
setPreferredSize(new Dimension(400, 300));
setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
JLabel converterName = new JLabel("Hexadecimal Input");
convert = new JButton ("Convert");
convert.addActionListener (new ButtonListener());
add (convert);
JPanel panelName = new JPanel(new GridLayout(2,2));
panelName.add(converterName);
panelName.add(hexdecString);
add(panelName, BorderLayout.NORTH);
JPanel totalPanel = new JPanel(new GridLayout(2,3));
totalPanel.add(new JLabel("Binary:"));
totalone = new JLabel("---- ---- ---- ---- ----");
totalPanel.add(totalone);
totalPanel.add(binaryLabel);
JPanel totalPanel2 = new JPanel(new GridLayout(2,3));
totalPanel2.add(new JLabel("Decimal:"));
totaltwo = new JLabel("------");
totalPanel2.add(totaltwo);
totalPanel2.add(decimalLabel);
JPanel south = new JPanel(new GridLayout(2,1));
south.add(totalPanel);
south.add(totalPanel2);
add(south, BorderLayout.SOUTH);
}
private class ButtonListener implements ActionListener {
public void actionPerformed (ActionEvent event){
Integer n = Integer.valueOf(hexdecString.getText(), 16);
decimalLabel.setText(String.valueOf(n));
binaryLabel.setText(Integer.toBinaryString(n));
}
}
}
答案 0 :(得分:0)
也许你想要这样的东西:
import java.util.Arrays;
...
Integer n = Integer.valueOf(hexdecString.getText(), 16);
decimalLabel.setText(String.valueOf(n));
// make an array of characters where each character
// is a '1' or '0' corresponding to the binary representation of n
char[] charArray = Integer.toBinaryString(n).toCharArray();
binaryLabel.setText(Arrays.toString(charArray));
将二进制字符串数组转换为二进制字符数组。这并不比你所拥有的更好,请注意,只是看起来与你所要求的相符。