2016-03-27 35 views
2

我正在編寫一個程序,通過JLabel數組和JTextfield的方式將十進制轉換爲二進制以供用戶輸入。我有一個Step按鈕,它可以將文本框中的十進制數字和每次按下時顯示的二進制數字相加。但是,當數字達到256時,它應該「繞回」到00000000,將1放在前面。我不知道如何在Listener中做到這一點,尤其是沒有訪問私有JLabel數組(因此爲什麼我不能只做一個「如果num等於256,然後數組將文本設置爲0」語句)。我所有使用的是文本框中的十進制數和小數點到二進制方法。我已經試過:如何在數組中將二進制數字「換行」爲0?

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

我看到兩個錯誤代碼

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體,且您重置boxi(而不是0)。像,

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