Jump to content

Basic Java Help Variable Resets when Calling Other Class

Go to solution Solved by Arberden,

A class stores nothing.

A class is more like a building guide for objects.

If you call the Constructor you basicaly create an object.

This object can store data in the predefined variables.

You can save the referenc to an Object to an Variable.

Database myDB = new Database();Database myDB2;myDB2 = myDB;

All the changes you make by calling the methods in myDB2 will also effcet myDB (and vice versa), as they both reference the same object you created with new Database()

So how do i call a method from another class without resetting its variables

 

Solved using static to call the methods so i do not need to declare the constructor

Hi guys,

I have this java project where I am creating a bank and when i call another class, the variable in the first class resets. I don't really know why. The first screen prompt the user to enter their AdmNo and PIN which is transferred into the Database with no problems.

Then, the second screen will have a prompt to enter in a pattern as a secondary password. When this happens, the variable storing the identity of the person(array) is being reset. Database is extends to the pattern.

 

This is the class for the Database.

 

    
//Method checkAdmNo checks the admno of the user and matches it to     //the AdmNo in the array to find which row it belongs to    public void checkAdmNo(int admno, int method) {        for(int i = 0; i < admNo.length; i++){        if ((admNo[i] != admno)) {            correct = false;            }        else {            array = i;            correct = true;            break;            }        }        if (correct==false)            System.out.println("Incorrect AdmNo or PIN");    }    //Using the row found above check the pin number of it to see if it matches    public void checkPIN(int PIN) {        if (correct) {            if ((pin[array] == PIN)) {                System.out.println("Welcome " + names[array] + " to DIT 22 Bank!\nEnter your pattern here.");                super.callPattern();                correct = false;            } else {                System.out.println("Incorrect AdmNo or PIN");                correct = false;                //reinvoke the bank screen to reenter AdmNo and PIN                Bank.main(names);            }        }    }        //Using the row found above check the pattern of it to see if it matches    //Currently does not work as the array variable is being reset    public void checkPattern(int pat) {                if (pattern[array] == pat) {            System.out.println("Welcome " + names[array] + " to DIT 22 Bank");        } else {            System.out.println("Incorrect Pattern");                //reinvoke the pattern screen to reenter pattern                super.callPattern();        }    }

This is the Pattern class

public void mouseReleased(MouseEvent e) {        //Set mouse holding down to false        holding = false;        //Re-enable Buttons        for (int i = 0; i < button1.length; i++) {            button1[i].setEnabled(true);        }        //call method in database to checkPattern        DataBase d = new DataBase();        d.checkPattern((Integer.parseInt(enteredPattern)));        dispose();    }

Sorry if its abit long so i included only the necessary parts.

Thanks for help in advance.

Link to comment
Share on other sites

Link to post
Share on other sites

can you use the code tag to make reading a bit easier next time please. It's the <> button in the normal editor under the :).

I don't use java, so don't know much about its specifics, but is the variable staying in scope? As far as I can tell, it seems to be a local variable, but you're trying to read it from another function, which is illegal in most languages. As I said though, I don't know much about java so I don't know.

HTTP/2 203

Link to comment
Share on other sites

Link to post
Share on other sites

What class are you extending? You are calling super.callPattern(). Did you write the class you are extending?

EDIT: Use code tags and post everything you have. Some stuff is missing and the code is hard to read in its current state.

Link to comment
Share on other sites

Link to post
Share on other sites

What class are you extending? You are calling super.callPattern(). Did you write the class you are extending?

EDIT: Use code tags and post everything you have. Some stuff is missing and the code is hard to read in its current state.

 

Sorry about that. I just added in code tags and it is extending to the pattern class.

Link to comment
Share on other sites

Link to post
Share on other sites

//Method checkAdmNo checks the admno of the user and matches it to     //the AdmNo in the array to find which row it belongs to    public void checkAdmNo(int admno, int method) {        correct = false        for(int i = 0; i < admNo.length; i++){        if ((admNo[i] == admno)) {  //Naming  is just terrible ...            array = i; // Naming a variable array -.- ....             correct = true;            break;            }        }        if (correct) // no need to compare as correct is a boolean ...            System.out.println("Incorrect AdmNo or PIN");    }

.... There is still too much code missing

Mini-Desktop: NCASE M1 Build Log
Mini-Server: M350 Build Log

Link to comment
Share on other sites

Link to post
Share on other sites

Sorry about that. I just added in code tags and it is extending to the pattern class.

Post everything. You have a lot of code missing.

Link to comment
Share on other sites

Link to post
Share on other sites

//Method checkAdmNo checks the admno of the user and matches it to     //the AdmNo in the array to find which row it belongs to    public void checkAdmNo(int admno, int method) {        correct = false        for(int i = 0; i < admNo.length; i++){        if ((admNo[i] == admno)) {  //Naming  is just terrible ...            array = i; // Naming a variable array -.- ....             correct = true;            break;            }        }        if (correct) // no need to compare as correct is a boolean ...            System.out.println("Incorrect AdmNo or PIN");    }

.... There is still too much code missing

 

 

While I agree that there is no need to compare for a bool, the thing is it is correct == false....so if(!correct), and given the ! can be overlooked sometimes I can understand how come some people would use == false, as it increases readability without any performance loss.

 

Hi guys,

I have this java project where I am creating a bank and when i call another class, the variable in the first class resets. I don't really know why. The first screen prompt the user to enter their AdmNo and PIN which is transferred into the Database with no problems.

Then, the second screen will have a prompt to enter in a pattern as a secondary password. When this happens, the variable storing the identity of the person(array) is being reset. Database is extends to the pattern.

 

This is the class for the Database.

 

    
//Method checkAdmNo checks the admno of the user and matches it to     //the AdmNo in the array to find which row it belongs to    public void checkAdmNo(int admno, int method) {        for(int i = 0; i < admNo.length; i++){        if ((admNo[i] != admno)) {            correct = false;            }        else {            array = i;            correct = true;            break;            }        }        if (correct==false)            System.out.println("Incorrect AdmNo or PIN");    }    //Using the row found above check the pin number of it to see if it matches    public void checkPIN(int PIN) {        if (correct) {            if ((pin[array] == PIN)) {                System.out.println("Welcome " + names[array] + " to DIT 22 Bank!\nEnter your pattern here.");                super.callPattern();                correct = false;            } else {                System.out.println("Incorrect AdmNo or PIN");                correct = false;                //reinvoke the bank screen to reenter AdmNo and PIN                Bank.main(names);            }        }    }        //Using the row found above check the pattern of it to see if it matches    //Currently does not work as the array variable is being reset    public void checkPattern(int pat) {                if (pattern[array] == pat) {            System.out.println("Welcome " + names[array] + " to DIT 22 Bank");        } else {            System.out.println("Incorrect Pattern");                //reinvoke the pattern screen to reenter pattern                super.callPattern();        }    }

This is the Pattern class

public void mouseReleased(MouseEvent e) {        //Set mouse holding down to false        holding = false;        //Re-enable Buttons        for (int i = 0; i < button1.length; i++) {            button1[i].setEnabled(true);        }        //call method in database to checkPattern        DataBase d = new DataBase();        d.checkPattern((Integer.parseInt(enteredPattern)));        dispose();    }

Sorry if its abit long so i included only the necessary parts.

Thanks for help in advance.

 

 

Like others have said, there is too much information missing to properly assess the problem.

 

If I had to guess it would be this portion

public void mouseReleased(MouseEvent e) {        //Set mouse holding down to false        holding = false;        //Re-enable Buttons        for (int i = 0; i < button1.length; i++) {            button1[i].setEnabled(true);        }        //call method in database to checkPattern        DataBase d = new DataBase();        d.checkPattern((Integer.parseInt(enteredPattern)));        dispose();    }

The DataBase d = new DataBase(); is probably not calling checkAdmNo.  As checkAdmNo is the only function that sets the array, creating a new Database and not calling the "checkAdmNo" will not initialize Array which is where the problem happens.

 

Now to discuss the other issues.

Naming convention is what can make or break your program.  While I agree with most of the names, there are some things that should be avoided (to ease the readability).  The most important thing calling an integer "array"...could be called something like AdminIndexNo, more descriptive and doesn't imply it is something it is not.  The other big issue is Adminno and AdminNo, AdminNo would ideally be AdminNoArray....anyways please take that into consideration.

 

As a little pointer, it can be helpful starting all internal variables with an _ that way you know it is internal and no conflicts with the parameter names.

0b10111010 10101101 11110000 00001101

Link to comment
Share on other sites

Link to post
Share on other sites

While I agree that there is no need to compare for a bool, the thing is it is correct == false....so if(!correct), and given the ! can be overlooked sometimes I can understand how come some people would use == false, as it increases readability without any performance loss.

 

Ah... oops. I originally changed it to (! correct) but deleted my entire post and than later started over again.

 

 

I wrote my last real piece of java code over 3 years ago in college.

Nowadays I only write some small vba-scripts and use a basic like language for simulations.

If you would want to keep the same functionalty I would write something like this.

public void checkAdmNo(int admno) {        for(int i = 0; i < admNo.length; i++) {            if ((admNo[i] = admno)) {                array = i;                return;             }         }        System.out.println("Incorrect AdmNo or PIN");}

Mini-Desktop: NCASE M1 Build Log
Mini-Server: M350 Build Log

Link to comment
Share on other sites

Link to post
Share on other sites

OK. i am posting all the codes here

 

Database code

public class DataBase extends Pattern {    //Declare Variables    boolean correct = false;    int adminIndexNo;    String names[] = {        "A",        "B",        "C",        "D",        "E",        "F",        "G",        "H",        "I",        "J",        "K",        "L",        "M",        "N",        "O",        "P",        "Q",        "R",        "S",        "T",        "U"    };    int admNo[] = {1333961,        1,        2,        3,        4,        5,        6,        7,        8,        9,        10,        11,        12,        13,        14,        15,        16,        17,        18,        19,        20    };       int pattern[] = {        12357,        12357,        12357,        12357,        12357,        12357,        12357,        12357,        12357,        12357,        12357,        12357,        12357,        12357,        12357,        12357,        12357,        12357,        12357,        12357,        12357,};    int pin[] = {        123456,        123456,        123456,        123456,        123456,        123456,        123456,        123456,        123456,        123456,        123456,        123456,        123456,        123456,        123456,        123456,        123456,        123456,        123456,        123456,        123456,};        double money[]={    2000,    2000,    2000,    2000,    2000,    2000,    2000,    2000,    2000,    2000,    2000,    2000,    2000,    2000,    2000,    2000,    2000,    2000,    2000,    2000,    2000,    };    //Declare Constructor so methods can be called    public DataBase() {           }        //Method checkAdmNo checks the admno of the user and matches it to     //the AdmNo in the adminIndexNo to find which row it belongs to    public void checkAdmNo(int admno, int method) {        for(int i = 0; i < admNo.length; i++){        if ((admNo[i] != admno)) {            correct = false;            }        else {            adminIndexNo = i;            correct = true;            break;            }        }        if (correct==false)            System.out.println("Incorrect AdmNo or PIN");    }    //Using the row found above check the pin number of it to see if it matches    public void checkPIN(int PIN) {        if (correct) {            if ((pin[adminIndexNo] == PIN)) {                System.out.println("Welcome " + names[adminIndexNo] + " to DIT 22 Bank!\nEnter your pattern here.");                super.callPattern();                correct = false;            } else {                System.out.println("Incorrect AdmNo or PIN");                correct = false;                //reinvoke the bank screen to reenter AdmNo and PIN                Bank.main(names);            }        }    }        //Using the row found above check the pattern of it to see if it matches    //Currently does not work as the adminIndexNo variable is being reset    public void checkPattern(int pat) {                if (pattern[adminIndexNo] == pat) {            System.out.println("Welcome " + names[adminIndexNo] + " to DIT 22 Bank");            Bank d = new Bank();            d.getMethod();        } else {            System.out.println("Incorrect Pattern");                super.callPattern();        }    }}

Bank code

public class Bank extends JFrame implements ActionListener{    //Declare variables    private JLabel Title,ID,Purpose;    private JComboBox Usage;    private JTextField Text1,Displayer;    private JButton SignUp,ResetPass;    private JButton button[]=new JButton[12];    String DisplayerStr="";    DataBase d = new DataBase();    Ding t = new Ding();    int method;    String enteredPin="";        //Constructor    public Bank(){                //Create all buttons/labels/comboBox etc.        setFont(new Font("TimeRoman",Font.PLAIN,24));                JPanel TopPanel = new JPanel();        TopPanel.setLayout(new FlowLayout(FlowLayout.CENTER));        Title= new JLabel("Bank");        Title.setForeground(Color.MAGENTA);        Title.setFont(new Font("TimeRoman",Font.PLAIN,50));        TopPanel.add(Title);        add(TopPanel,BorderLayout.NORTH);                JPanel CenterPanel = new JPanel();        CenterPanel.setLayout(new BorderLayout());        add(CenterPanel,BorderLayout.CENTER);                JPanel InputPanel = new JPanel();        InputPanel.setLayout(new GridLayout(3,2,0,31));        InputPanel.setBorder(BorderFactory.createTitledBorder("Credentials"));        InputPanel.add(ID= new JLabel("User ID      :"));        InputPanel.add(Text1= new JTextField(10));        InputPanel.add(Purpose = new JLabel("Purpose    :"));        InputPanel.add(Usage= new JComboBox(new String[]{"Withdraw","Deposit","Transfer","Statement","Change Pin"}));        InputPanel.add(SignUp= new JButton("Sign Up"));        InputPanel.add(ResetPass= new JButton("Forget Password"));        CenterPanel.add(InputPanel,BorderLayout.WEST);                JPanel Number = new JPanel();        Number.setLayout(new BorderLayout());                JPanel PIN= new JPanel();        PIN.setLayout(new GridLayout(4,3));        PIN.setBorder(BorderFactory.createTitledBorder("PIN Number"));        for (int number=1; number<=9; number++)            PIN.add(button[number]=new JButton(Integer.toString(number)));        PIN.add(button[10]=new JButton("Enter"));        PIN.add(button[0]=new JButton("0"));        PIN.add(button[11]=new JButton("Reset"));        Number.add(PIN,BorderLayout.NORTH);                JPanel Display = new JPanel();        Display.setLayout(new BorderLayout());        Display.setBorder(BorderFactory.createTitledBorder("Entered number :"));        Display.add(Displayer= new JTextField(10));        Number.add(Display,BorderLayout.CENTER);                CenterPanel.add(Number,BorderLayout.EAST);                //add action listener to all                button[0].addActionListener(this);                button[1].addActionListener(this);                button[2].addActionListener(this);                button[3].addActionListener(this);                button[4].addActionListener(this);                button[5].addActionListener(this);                button[6].addActionListener(this);                button[7].addActionListener(this);                button[8].addActionListener(this);                button[9].addActionListener(this);                button[10].addActionListener(this);                button[11].addActionListener(this);                SignUp.addActionListener(this);                ResetPass.addActionListener(this);                Usage.addActionListener(this);                Text1.addActionListener(this);                //make displayer uneditable                Displayer.setEditable(false);        }//action performed        public void actionPerformed(ActionEvent e){            //display X when a number is pressed            if(e.getSource()==button[0]){                enteredPin+= "0";                DisplayerStr+="X";}            else if(e.getSource()==button[1]){                enteredPin+= "1";                DisplayerStr+="X";}            else if(e.getSource()==button[2]){                enteredPin+= "2";                DisplayerStr+="X";}            else if(e.getSource()==button[3]){                enteredPin+= "3";                DisplayerStr+="X";}            else if(e.getSource()==button[4]){                enteredPin+= "4";                DisplayerStr+="X";}            else if(e.getSource()==button[5]){                enteredPin+= "5";                DisplayerStr+="X";}            else if(e.getSource()==button[6]){                enteredPin+= "6";                DisplayerStr+="X";}            else if(e.getSource()==button[7]){                enteredPin+= "7";                DisplayerStr+="X";}            else if(e.getSource()==button[8]){                enteredPin+= "8";                DisplayerStr+="X";}            else if(e.getSource()==button[9]){                enteredPin+= "9";                DisplayerStr+="X";}            if(e.getSource()==button[0]||e.getSource()==button[1]||e.getSource()==button[2]||e.getSource()==button[3]||e.getSource()==button[4]||e.getSource()==button[5]||e.getSource()==button[6]||e.getSource()==button[7]||e.getSource()==button[8]||e.getSource()==button[9]){                //update onto the screen                Displayer.setText(DisplayerStr);                //add a - after the X but is not refreshed                DisplayerStr+="-";}                   //get the input option on ComboBox            if (e.getSource()==Usage){        JComboBox Usage=(JComboBox) e.getSource();            String s =(String) Usage.getItemAt(Usage.getSelectedIndex());            if (s== "Withdraw"){                System.out.println("Withdraw");                method=1;            }            else if(s=="Deposit"){                System.out.println("Deposit");                method=2;            }            else if(s=="Transfer"){                System.out.println("Transfer");                method=3;            }            else if(s=="Statement"){                System.out.println("Statement");                method=4;            }            else if(s=="Change Pin"){                System.out.println("Change Pin");                   method=5;            }                    }            //enter button            if(e.getSource()==button[10]){                //call methods in database to check if admno and pin are accurate        d.checkAdmNo((Integer.parseInt(Text1.getText())),method);        d.checkPIN(Integer.parseInt(enteredPin));        //dispose it        dispose();                    }                    //reset button        if (e.getSource()==button[11]){        enteredPin = "";        DisplayerStr = "";        Displayer.setText(DisplayerStr);        Text1.setText("");            }        }                //get the method from JComboBox        public void getMethod(){            Deposit d=new Deposit();                           Withdraw w=new Withdraw();            switch(method){            case(1):w.callWithdraw();                    break;            case(2):d.callDeposit();                    break;            }        }        //main        public static void main(String[] args) {        Bank frame= new Bank();        frame.setTitle("Bank");        frame.pack();        frame.setLocationRelativeTo(null);        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);        frame.setVisible(true);        frame.setResizable(false);    }    }       

Pattern code

public class Pattern extends JFrame implements MouseListener {    //Variable Declaration    private JButton button1[] = new JButton[9];    boolean holding = false;    private static boolean btn0Clicked = false, btn1Clicked = false, btn2Clicked = false, btn3Clicked = false,            btn4Clicked = false, btn5Clicked = false, btn6Clicked = false, btn7Clicked = false,            btn8Clicked = false;    String enteredPattern = "";    //Constructor    public Pattern() {        JPanel b = new JPanel();        b.setLayout(new GridLayout(3, 3, 50, 30));        //Creating Buttons        for (int i = 0; i < button1.length; i++) {            button1[i] = new JButton();            button1[i].setText(Integer.toString(i + 1));            b.add(button1[i]);            button1[i].addMouseListener(this);        }        add(b);    }    //Mouse event mouse pressed    public void mousePressed(MouseEvent e) {        //Set the holding down mouse is true        holding = true;        //Get the first button pressed        for (int i = 0; i < button1.length; i++) {            if (e.getSource() == button1[i]) {                enteredPattern = (Integer.toString(i + 1));            }        }    }    //Mouse event mouse entered    public void mouseEntered(MouseEvent e) {        //Check if mouse is held down        if (holding) {            for (int i = 0; i < button1.length; i++) {                if ((e.getSource() == button1[i]) && button1[i].isEnabled()) {                    //check when mouse mouses over a button and the button is enabled                    //add moused over button to enteredPattern and disable it                    button1[i].setEnabled(false);                    enteredPattern += (Integer.toString(i + 1));                }            }        }    }    //Mouse event mouse released    public void mouseReleased(MouseEvent e) {        //Set mouse holding down to false        holding = false;        //Re-enable Buttons        for (int i = 0; i < button1.length; i++) {            button1[i].setEnabled(true);        }        //call method in database to checkPattern        DataBase d = new DataBase();        d.checkPattern((Integer.parseInt(enteredPattern)));        dispose();    }    //Just here to allow program to run    public void mouseClicked(MouseEvent e) {    }    //Just here to allow program to run    public void mouseExited(MouseEvent e) {    }    //method call pattern    public void callPattern() {        Pattern frame = new Pattern();        frame.setTitle("Pattern");        frame.setSize(500, 200);        frame.setLocationRelativeTo(null);        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);        frame.setVisible(true);    }}
Link to comment
Share on other sites

Link to post
Share on other sites

I think i found the error. Everytime i declare the constructor like this

DataBase d=new DataBase();

The variables in database gets reset.

Am i right?

Link to comment
Share on other sites

Link to post
Share on other sites

I think i found the error. Everytime i declare the constructor like this

DataBase d=new DataBase();

The variables in database gets reset.

Am i right?

Everytime you call the constructor a new instance is created, so yes all variable are reset.

 

You should really work on your java wirting skills (naming convetions etc.)

If I would have showed something like this to my lecturer, he would have probably given me zero points.

Mini-Desktop: NCASE M1 Build Log
Mini-Server: M350 Build Log

Link to comment
Share on other sites

Link to post
Share on other sites

Everytime you call the constructor a new instance is created, so yes all variable are reset.

 

You should really work on your java wirting skills (naming convetions etc.)

If I would have showed something like this to my lecturer, he would have probably given me zero points.

So how should i call another class if i want to keep the variables.

Sorry i'm still new to java

Link to comment
Share on other sites

Link to post
Share on other sites

So how should i call another class if i want to keep the variables.

Sorry i'm still new to java

 

You don't call the class, but rather the methods in the class.

Store the reference to one instance of the Class (e.g. Databse) in a variable and use it

Database myDB= new Database(); // only call the constructor oncemyDB.method1();myDB.method2();

If you want to use the same database in another class, hust pass the reference as paramter in a funciton call.

---------

Also mixing of functional code and GUI is terrible :/

Why don't just make it textbased, before messing around with GUI?

Mini-Desktop: NCASE M1 Build Log
Mini-Server: M350 Build Log

Link to comment
Share on other sites

Link to post
Share on other sites

A class stores nothing.

A class is more like a building guide for objects.

If you call the Constructor you basicaly create an object.

This object can store data in the predefined variables.

You can save the referenc to an Object to an Variable.

Database myDB = new Database();Database myDB2;myDB2 = myDB;

All the changes you make by calling the methods in myDB2 will also effcet myDB (and vice versa), as they both reference the same object you created with new Database()

Mini-Desktop: NCASE M1 Build Log
Mini-Server: M350 Build Log

Link to comment
Share on other sites

Link to post
Share on other sites

A class stores nothing.

A class is more like a building guide for objects.

If you call the Constructor you basicaly create an object.

This object can store data in the predefined variables.

You can save the referenc to an Object to an Variable.

Database myDB = new Database();Database myDB2;myDB2 = myDB;

All the changes you make by calling the methods in myDB2 will also effcet myDB (and vice versa), as they both reference the same object you created with new Database()

So how do i call a method from another class without resetting its variables

 

Solved using static to call the methods so i do not need to declare the constructor

Link to comment
Share on other sites

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×