2016-03-27 7 views
2

私は、JLabel配列とJTextfieldを使用してユーザー入力用に10進数から2進数に変換するプログラムを作成しています。私は、テキストボックスの10進数と押されるたびに表示される2進数の両方に1を加えるステップボタンを持っています。しかし、その数が256になると、00000000に "ラップアラウンド(wrap around)"され、1を前に置くことになっています。私はリスナーでこれを行う方法がわかりません。特にプライベートJLabel配列へのアクセスがないためです(なぜnumが256の場合は配列が0になるようにすることはできません)。は、テキストボックスの10進数と2進法の10進数です。バイナリ数を配列内で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

私はコード内の2つのバグ

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身体を終了し、あなたは(0の代わりに)iboxをリセットします。同様に、

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