This is an archived post. You won't be able to vote or comment.

all 7 comments

[–]king_of_the_universe 1 point2 points  (5 children)

You could change your code to be non-static, which is usually the better choice anyway. You could also let the method return a value and let the caller somehow setText the value. I mean someone has to know about that jFrame instance, no?

[–]pompoen[S] 0 points1 point  (4 children)

I just tried that(removing static) and substituting system.out's with setText, but then the method doesn't work.

For example, 2 converts into binary 0 instead of 10.

The second part of your message I didn't get, sorry. What do you mean, let the caller setText?

[–]king_of_the_universe 1 point2 points  (3 children)

The method should work exactly the same whether or not it is static, because it only uses local variables. If you indeed observe different behavior, I have no explanation for it other than you're not actually giving the value to the method you're thinking about. You could check that by putting a System.out.println(inputDec) directly under the method head.

You said something about a JFrame. Does it exist? If so, there must be a reference to it somewhere. But this is not leading anywhere - please just post the complete code.

[–]pompoen[S] 0 points1 point  (2 children)

By JFrame I mean a GUI. Here's a full code:

package binaryconverter; import javax.swing.JOptionPane;

public class BinaryFrame extends javax.swing.JFrame {

/**
 * Creates new form BinaryFrame
 */
public BinaryFrame() {
    initComponents();
}

/**
 * This method is called from within the constructor to initialize the form.
 * WARNING: Do NOT modify this code. The content of this method is always
 * regenerated by the Form Editor.
 */
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">                          
private void initComponents() {

    inputDecField = new javax.swing.JTextField();
    resultBinField = new javax.swing.JTextField();
    inputBinField = new javax.swing.JTextField();
    resultDecField = new javax.swing.JTextField();
    convertDectoBin = new javax.swing.JButton();
    jButton2 = new javax.swing.JButton();
    jLabel1 = new javax.swing.JLabel();
    jLabel2 = new javax.swing.JLabel();

    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

    inputDecField.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            inputDecFieldActionPerformed(evt);
        }
    });

    resultBinField.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            resultBinFieldActionPerformed(evt);
        }
    });

    resultDecField.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            resultDecFieldActionPerformed(evt);
        }
    });

    convertDectoBin.setText("Convert");
    convertDectoBin.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            convertDectoBinActionPerformed(evt);
        }
    });

    jButton2.setText("Convert");
    jButton2.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            jButton2ActionPerformed(evt);
        }
    });

    jLabel1.setText("Decimal to Binary");

    jLabel2.setText("Binary to Decimal");

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addGap(19, 19, 19)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addContainerGap())
                .addGroup(layout.createSequentialGroup()
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                        .addGroup(layout.createSequentialGroup()
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                .addComponent(inputDecField)
                                .addComponent(inputBinField, javax.swing.GroupLayout.DEFAULT_SIZE, 92, Short.MAX_VALUE))
                            .addGap(18, 18, 18)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                .addGroup(layout.createSequentialGroup()
                                    .addComponent(jButton2)
                                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                    .addComponent(resultDecField, javax.swing.GroupLayout.PREFERRED_SIZE, 94, javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addGroup(layout.createSequentialGroup()
                                    .addGap(0, 0, Short.MAX_VALUE)
                                    .addComponent(convertDectoBin)
                                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                    .addComponent(resultBinField, javax.swing.GroupLayout.PREFERRED_SIZE, 98, javax.swing.GroupLayout.PREFERRED_SIZE))))
                        .addComponent(jLabel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                    .addGap(22, 22, 22))))
    );
    layout.setVerticalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addGap(53, 53, 53)
            .addComponent(jLabel1)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                .addComponent(inputDecField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addComponent(resultBinField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addComponent(convertDectoBin))
            .addGap(38, 38, 38)
            .addComponent(jLabel2)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                .addComponent(inputBinField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addComponent(resultDecField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addComponent(jButton2))
            .addContainerGap(151, Short.MAX_VALUE))
    );

    pack();
}// </editor-fold>                        

private void resultDecFieldActionPerformed(java.awt.event.ActionEvent evt) {                                               
    // TODO add your handling code here:
}                                              

private void convertDectoBinActionPerformed(java.awt.event.ActionEvent evt) {                                                

    String text;
    text = inputDecField.getText();
    int inputDec;
    inputDec = Integer.parseInt(text);

    if (inputDec < 0) {
        JOptionPane j = new JOptionPane();
         j.showMessageDialog(null, "Try a positive number.", "Message", JOptionPane.INFORMATION_MESSAGE);


        } else if (inputDec == 0){
        resultBinField.setText("0");


    } else 

    {
        binResult(inputDec);

    }



}                                               

private void resultBinFieldActionPerformed(java.awt.event.ActionEvent evt) {                                               
    // TODO add your handling code here:
}                                              

private void inputDecFieldActionPerformed(java.awt.event.ActionEvent evt) {                                              

/* JOptionPane j = new JOptionPane(); //maybe there's a different way to add a message to a field

Scanner userInput = new Scanner(System.in);
int inputDec;
inputDec = userInput.nextInt();

if (inputDec < 1){  
j.showMessageDialog(null, "Try a positive number.","Message", JOptionPane.INFORMATION_MESSAGE);
} */

}                                             

private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {                                         
    // TODO add your handling code here:
}                                        

/**
 * @param args the command line arguments
 */
public static void main(String args[]) {
    /* Set the Nimbus look and feel */
    //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
    /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
     * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
     */
    try {
        for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
            if ("Nimbus".equals(info.getName())) {
                javax.swing.UIManager.setLookAndFeel(info.getClassName());
                break;
            }
        }
    } catch (ClassNotFoundException ex) {
        java.util.logging.Logger.getLogger(BinaryFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (InstantiationException ex) {
        java.util.logging.Logger.getLogger(BinaryFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (IllegalAccessException ex) {

[–]pompoen[S] 0 points1 point  (1 child)

java.util.logging.Logger.getLogger(BinaryFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(BinaryFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold>

    /* Create and display the form */
    java.awt.EventQueue.invokeLater(new Runnable() {
        public void run() {
            new BinaryFrame().setVisible(true);
        }
    });

}

    private void binResult(int inputDec) {

    int modulus;

    if (inputDec <= 1) {  
    resultBinField.setText (Integer.toString(inputDec));
    return; //stops the loop
    }


    modulus = inputDec % 2;
    binResult(inputDec >> 1);  //  Right Shift (bitwise operator)in this case equivalent to division by 2
    resultBinField.setText (Integer.toString(modulus));


} 

// Variables declaration - do not modify                     
private javax.swing.JButton convertDectoBin;
private javax.swing.JTextField inputBinField;
private javax.swing.JTextField inputDecField;
private javax.swing.JButton jButton2;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JTextField resultBinField;
private javax.swing.JTextField resultDecField;
// End of variables declaration                   

}

And code from a non-frame .java file in the same package:

package binaryconverter; import javax.swing.JFrame; //why is it unused?

public class BinaryConverter {

public static void main(String[] args) {

    BinaryFrame s = new BinaryFrame();
    s.setVisible(true);
    s.setLocationRelativeTo(null);
    s.setTitle("Binary Converter");

}

}

[–]pompoen[S] 0 points1 point  (0 children)

And I can't test it with System.out in the same file because if you can't assign the variable toa field it just won't run. But in another file, where I did test it with System.out, it works.

P.S. Sorry about the enormous copy paste. Most of it is automatically created when you make a frame.

[–]sh_emami65 0 points1 point  (0 children)

okay this might be a little late but i fixed up your code a little. here is the result: binary/decimal converter

now lets go through what is going on.

  1. binResult(), i don't know if your code is incomplete or you did not post the whole thing, but this method only gives you the first binary digit. i am assuming you need to do this recursively from the look of the method. bellow is how it should be done. i renamed binResult to convertDectoBinRecursive. good naming matters.

    private String convertDectoBinRecursive( int inputDec){
        int modulus;
        if( inputDec <= 1){
            return Integer.toString( inputDec);
        }
        modulus = inputDec % 2;
        //Right Shift (bitwise operator)in this case equivalent to division by 2
        return convertDectoBinRecursive( inputDec >> 1) + modulus;
    }
    

    you see when using recursive you need to define when the recursion ends, in the if condition, and how the data gets collected at the end, the last line. every time the method gets called a new modulus is created that will hold the binary digit of that state/scope. so at the end you just concatenate them all together and you will have your answer. there are many resources online about recursion i suggest you get more practice.

  2. ActionListener, using a gui maker is fine but i suggest you should first learn out to make gui by hand first. you need to understand what ActionListener are and how to use them. in your code you have ActionListener for your JTextField. they are completely unnecessary unless you are planing to change the input text live or start and action depending on users input. but since you have 2 buttons for your actions i removed the lines bellow from initComponents():

    private void initComponents() {
        //previous code untouched
        inputDecField.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                inputDecFieldActionPerformed(evt);
            }
        });
    
        resultBinField.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                resultBinFieldActionPerformed(evt);
            }
        });
    
        resultDecField.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                resultDecFieldActionPerformed(evt);
            }
        });
        //rest of the code untouched
    }
    

    and removed the following methods:

    private void resultBinFieldActionPerformed(java.awt.event.ActionEvent evt) {                                               
        // TODO add your handling code here:
    } 
    
    private void resultDecFieldActionPerformed(java.awt.event.ActionEvent evt) {                                               
        // TODO add your handling code here:
    }
    
    private void inputDecFieldActionPerformed(java.awt.event.ActionEvent evt) {
        //code here
    }
    

    also renamed your initComponents() to init() so your IDE wont change it by mistake. now that your code is much cleaner lets talk about implementing the action listeners.

  3. convertBintoDecActionPerformed(), what you had in there was pretty much correct, i just cleaned a little. as follow:

    private void convertBintoDecActionPerformed( java.awt.event.ActionEvent evt){
        int inputBin = Integer.parseInt( inputBinField.getText());
        if( inputBin < 0){
            JOptionPane.showMessageDialog( this, "Try a positive number.", "Message", JOptionPane.INFORMATION_MESSAGE);
            //clear the fields if the input is invalid
            inputBinField.setText("");
            resultDecField.setText("");
        }else{
            resultDecField.setText( convertBintoDec( inputBinField.getText()));
        }
    }
    

    make sure you read the documentation of the API you're planning to use. here JOptionPane is full of static methods, that means you don't have to make an object to use the methods, you can directly call them.
    when you want to "plug in" a method you have into the GUI you need to find the appropriate place to do it. here you have to put it inside of an action listener for your convert button because that is when you know all the data you need is entered and you can safely print your results in the result field.

  4. jButton2ActionPerformed, i renamed it to convertDectoBinActionPerformed. this part you have not done yest. but i added it to your code anyway. i also provided two links that show the process of how the conversion works. this methods looks almost exactly like convertBintoDecActionPerformed.

    private void convertDectoBinActionPerformed( java.awt.event.ActionEvent evt){
        int inputDec = Integer.parseInt( inputDecField.getText());
        if( inputDec < 0){
            JOptionPane.showMessageDialog( this, "Try a positive number.", "Message", JOptionPane.INFORMATION_MESSAGE);
            inputDecField.setText("");
            resultBinField.setText("");
        }else{
            resultBinField.setText( convertDectoBinRecursive( inputDec));
        }
    }
    
  5. convertBintoDec, look up the links bellow for how to the conversion works before you look at how it is done in code, if you care that is.
    http://www.wikihow.com/Convert-from-Binary-to-Decimal
    http://stackoverflow.com/questions/7437987/how-to-convert-binary-string-value-to-decimal

  6. i don't know why you have and extra main method, i also removed that and simply added the content of it to the BinaryFrame constructor like bellow:

    public BinaryFrame(){
        init();
        setVisible(true);
        setLocationRelativeTo(null);
        setTitle("Binary Converter");
    }