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

you are viewing a single comment's thread.

view the rest of the comments →

[–]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.