如何制作二进制数"环绕"在数组中为0?

时间:2016-03-27 22:01:43

标签: java arrays

我正在编写一个程序,通过JLabel数组转换十进制到二进制,并为用户输入转换JTextfield。我有一个Step按钮,它会在文本框中添加一个十进制数字,并在每次按下时显示二进制数字。然而,当数字达到256时,它应该被包围在#34;到00000000,将1放在前面。我不确定如何在Listener中执行此操作,尤其是在无法访问私有JLabel数组的情况下(因此我无法执行"如果num等于256,则数组将文本设置为0& #34;声明。)我必须使用的是文本框中的十进制数和十进制到二进制的方法。我试过了:

int i = Integer.parseInt(box.getText());

if(i == 256);
 {
   display.setValue(0); //setValue is method to convert dec. to binary
   box.setText("" + i); //box is the JTextfield that decimal # is entered in
  }

 if(i == 256)
   {
    i = i - i; 
    display.setValue(i); 
    } 

但他们都没有工作,我没有想法。我很感激一些帮助。很抱歉这个冗长的解释并提前致谢!

public class Display11 extends JPanel
   {
    private JLabel[] output;
    private int[] bits;
    public Display11()
    {
   public void setValue(int num)//METHOD TO CONVERT DECIMAL TO BINARY
  {
    for(int x = 0; x < 8; x++) //reset display to 0
     {
      bits[x] = 0;
     }
    int index = 0; //increments in place of a for loop
    while(num > 0) 
   {
    int temp = num%2; //gives lowest bit 
    bits[bits.length - 1 - index] = temp; //set temp to end of array
    index++; 
    num = num / 2; //updates num 

    if(num == 0) //0 case
    {
     for(int x = 0; x < 8; x++)
      {
       output[x].setText("0");
      }
    }

   }
    for(int x = 0; x < bits.length; x++)
    {
    output[x].setText("" + bits[x]); //output is the JLabel array
    }                                //bits is a temporary int array

    //display the binary number in the JLabel

   public class Panel11 extends JPanel
   {
    private JTextField box;
    private JLabel label;
    private Display11 display;
    private JButton button2;
    public Panel11()
    {
     private class Listener2 implements ActionListener //listener for the incrementing button
      {
      public void actionPerformed(ActionEvent e)
      {

       int i = Integer.parseInt(box.getText()); //increments decimal # 
       i++; 
       box.setText("" + i); 
       display.setValue(i); //converts incremented decimal # to binary

     }

  }

1 个答案:

答案 0 :(得分:1)

我在代码中看到两个错误

if(i == 256);
{
    display.setValue(0); //setValue is method to convert dec. to binary
    box.setText("" + i); //box is the JTextfield that decimal # is entered in
}

分号终止if正文,您将box重置为i(而不是0)。像,

if (i == 256)
{
    display.setValue(0);
    box.setText("0");
    i = 0; // <-- in case something else depends on i
}