Programming Forums

Programming Forums (http://www.programmingforums.org/forumindex.php)
-   Java (http://www.programmingforums.org/forum17.html)
-   -   retaining values in methods (http://www.programmingforums.org/showthread.php?t=14647)

nightFix Nov 30th, 2007 1:19 PM

retaining values in methods
 
Hello,
I'm pretty new to OOP and Jave and have ran into an issue on how to code some logic. I have a method that's needing to hold a local variables value upon different calls. I have tried this code but realize that Java can only use static keyword for classes. ( I think i have the code right, my code came off of a different computer that does not have internet access. I think I have remembered it correctly though.)
:

private float proc(int a, int b, boolean state){
if(state == true){
            //do processing here
            static int complete = 1;
            return result;
}else{
if(complete != 1){
            //do same processing here
}
// more processing
return result;
}

I then switched it to this but Java won't compile it due to a possible initiation issue.
:

private float proc(int a, int b, boolean state){
Integer completed;
if(state == true){
            //do processing here
            completed = 1;
            return result;
}else{
if(completed != 1){
            //do same processing here
}
// more processing
return result;
}

Any advice will greatly be appreciated.

titaniumdecoy Nov 30th, 2007 1:39 PM

Re: retaining values in methods
 
You can declare the variable outside the method as a private class variable:

:

private int complete;
...
private float proc(int a, int b, boolean state) { ... }


null_ptr0 Dec 1st, 2007 10:56 AM

Re: retaining values in methods
 
:

private float proc(int a, int b, boolean state) {
    int completed = 0;
    if(state) {
        //do processing here
        completed = 1;
        return result; //not defined???
    }
    //no need for the else block or completed value check, if it was state it would have returned, if it was not it would have gone here.
    //do same processing
    //more processing
    return result; //not defined???
}

titaniumdecoy, since Java is 'pure' OOP, they are called fields, not variables. And they are not called private class fields; a private class field is
:

private static int complete;
; what you mean is a private instance field, and not a local method field.

And nightFix, the error is because in Java, fields aren't auto initialized like in C++, you need to declare complete as a new Integer object type with the value as the constructor argument; but you should instead just declare it as a primitive 'int'. Primitives to Object types is not an optimization.

nightFix Dec 1st, 2007 11:15 AM

Re: retaining values in methods
 
Hey,
thank you for the input and quick responses. Null you are right I don't need an else there! Though I don't know if that affects processing time. I was using an Integer object rather than an int declaration because I was told that you can't pass primitive data types by reference nor can you get them to retain their value with different calls unless they are an object. Like I said I'm new to this and am probably needing to review my private vs public uses. Well I'm in a hurry right now but I still haven't got this code working. Hold the posts till I can get some code up later today. I appreciate the replies though and setting me on the right track.
Thanks a lot.

Jimbo Dec 1st, 2007 1:06 PM

Re: retaining values in methods
 
Quote:

Originally Posted by null_ptr0 (Post 137888)
And nightFix, the error is because in Java, fields aren't auto initialized like in C++, you need to declare complete as a new Integer object type with the value as the constructor argument

Slightly incorrect. C++ doesn't initialize fields/variables, but Java will initialize primitives to 0 and objects to null. C++ will call the default constructor for an object at instantiation if no other constructor is given (and probably for a class field as well - they're kinda weird) but a pointer to an object is a primitive and will not be initialized; the default constructor will likely initialize the variables, but that's up to the class' author.

nightFix Dec 4th, 2007 4:50 PM

Re: retaining values in methods
 
OK.
Sorry it took me so long to get back to you all.
Well I almost have my code working and believe I am using my access modifiers correctly but have never really used them before so if anyone picks up on a better way to do this than it will be considered.
My problem now, is that when my clear() method is called it throws an exception.
I've narrowed it down to the my JTextFields you will see identified as txtXXXX.
I have a feeling this is probably something simple but for some reason I'm not seeing it. Exception handling with Java is pretty new to me as well. I think I'm posting enough code to make it interpretable. Thanks for bearing with me.
:

public class PointOfSale extends JFrame implements ActionListener, ItemListener{

        //class variables
        JTextArea viewport1 = new JTextArea(3,20);
    JTextPane viewport2 = new JTextPane();

        int quant;
        float price;
        String item;
 
    //static vars for ctrl break and accumulated total
        static String nameHolder = "";
        static float total;
       



public void actionPerformed(ActionEvent e){
                try{
                        int index;
                        int id;
                        int quant;
                        String arg = e.getActionCommand();
                        String name = txtLname.getText();

                        quant = comboQty.getSelectedIndex() + 1;
                        id = Integer.parseInt(txtID.getText());
                        index = furnCombo.getSelectedIndex();
                        item = catalog[index];
                        price = Float.valueOf(txtPrice.getText());

                        if(e.getSource() == btnPCheck || arg == "Price Check"){
                                price = proc(quant, index, false);
                        }
                        if(e.getSource() == btnProc || arg == "Process"){
                                if(name.compareTo("") == 0 || price < 1) throw new NumberFormatException();
                               
                                viewport1.setText("");
                                if(name.compareTo(nameHolder) != 0){
                                        total = 0;
                                }
                                price = proc(quant, index, true);
                                nameHolder = name;
                                total += price;
                                clear();
                        }

                        if(e.getSource() == btnFinal){
                                viewport1.setText("");
                                viewport2.setText("");
                                JOptionPane.showMessageDialog(null, "Confirm total: " + total, "Confirm", JOptionPane.INFORMATION_MESSAGE);


                                }
                        if(e.getSource() == btnClear || arg == "Clear"){
                                clear();
                        }
                        if(e.getSource() == btnSysClear || arg == "SysClear"){
                                clear();
                        }

                        if(e.getSource() == btnExit || arg == "Exit")
                                System.exit(0);

                }
                catch(NumberFormatException nFx){
                        JOptionPane.showMessageDialog(null, "You have entered an incorrect value.", "Format Error", JOptionPane.ERROR_MESSAGE);
                }
                catch(Exception x){
                        JOptionPane.showMessageDialog(null, "An Error has occured.");
                }
                finally{
                System.out.println("exception cleanup");
                }

        }//end actionPerformed


        private float carryCharge;
        private int pCheckFlag;
        private float proc(int quant, int itemKey, boolean taxInc){
                        float tax;

                        if(taxInc == false){
                                float discount = 100 * (discountKey[itemKey]);
                                float discountAmt = (float) price * (discountKey[itemKey]);
                                price = (price * quant) - discountAmt;
                                print2viewport1(discount, discountAmt, price);
                                carryCharge = price;
                                pCheckFlag = 1;
                                return price;
                        }else{
                                if(pCheckFlag != 1){
                                price = proc(quant, itemKey, false);
                                viewport1.setText("");
                                }
                                tax = getTax();
                                price = carryCharge + (carryCharge * tax);
                                viewport2 = print2viewport2();
                                pCheckFlag = 0;
                                return carryCharge;
                                }
                }//end proc

private void clear(){
                        //txtfields throwing errors
                        txtID.setText("");
                        txtPrice.setText("");
                        //txtLname.setText("");
                        furnCombo.setSelectedIndex(0);
                        comboQty.setSelectedIndex(0);
                        rbTax[5].setSelected(true);
                      viewport1.setText("");
    }//end clear


nightFix Dec 5th, 2007 12:14 PM

Re: retaining values in methods
 
All right. So it only crashes if you clear while the fields are blank. The way I have it written the input is being tried above the clear actions so obviously if a user presses clear while there are empty text fields this will throw an exception! (you all need an emo face that slaps his head.)
I moved my clear actions above the initiations to keep it from crashing. I think this is proper.

:

public void actionPerformed(ActionEvent e){

                try{
                        String arg = e.getActionCommand();
                        if(e.getSource() == btnClear || arg == "Clear"){
                                clear();
                                return;
                        }
                        if(e.getSource() == btnSysClear || arg == "SysClear"){
                                sysClear();
                                return;
                        }
                        if(e.getSource() == btnExit || arg == "Exit")
                                System.exit(0);
                        int index;
                        int id;
                        int quant;
                        String name = txtLname.getText();

                        quant = comboQty.getSelectedIndex() + 1;
                        id = Integer.parseInt(txtID.getText());

                        index = furnCombo.getSelectedIndex();
                        item = catalog[index];
                        price = Float.parseFloat(txtPrice.getText());

                        //*****  price chek  ******
                        if(e.getSource() == btnPCheck || arg == "Price Check"){
                                price = proc(quant, index, false);
                        }

                        //***** process  **********
                        if(e.getSource() == btnProc || arg == "Process"){
                                if(name.compareTo("") == 0 || price < 1) throw new            NumberFormatException();
                                viewport1.setText("");
                                if(name.compareTo(nameHolder) != 0)
                                        total = 0;
                                price = proc(quant, index, true);
                                nameHolder = name;
                                total += price;
                                clear();
                        }

                       
                }
                catch(NumberFormatException nFx){
                        JOptionPane.showMessageDialog(null, "You have entered an incorrect value.", "Format Error", JOptionPane.ERROR_MESSAGE);
                }
                catch(Exception x){
                        JOptionPane.showMessageDialog(null, "An Error has occured.");
                }
                finally{
                System.out.println("exception cleanup");
                }

        }//end actionPerformed



All times are GMT -5. The time now is 3:51 AM.

Powered by vBulletin® Version 3.7.0, Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
Copyright ©2007 DaniWeb® LLC