rem208
rem208

Reputation: 79

value is not stored in variable between differente methods (beginner java project)

I have here two methods, the first one generate an student Id and store it an a value, this method works perfectly and the value is stored, but in the second mehtod when I take that variable from the first method on show that it is 0, what is the problem here ?

p.s. I worked with another method that return a string

// generate a student id 

        public int studentid(int grade) {
            System.out.println("now we gonna gerate an id number ");

            int id = grade * 10000;
            int t = 1000;
             
            for(int i = 0; i<4 ; i++) {
                int random = (int)(Math.random() * 9);
                random =  random * t;
                id = id + random;
                t = t / 10;
            }
            System.out.println("your id number is : " + id);
            return id;

            
            
        }
    
     
     
            
    // show name , id , grade and course enrolled 
    public void getInfo() {
        System.out.println("Student's First name: " + FirstName);
        System.out.println("Student's Last name: " +  LastName);
        System.out.println("Student's grade year: " + grade);
        System.out.println("Student's id number: " + id); 
        System.out.println("Student's courses: " + v); 

    }

now we gonna gerate an id number 
your id number is : 88222
Student's First name: luke
Student's Last name: goob
Student's grade year: 8
Student's id number: 0
Student's courses: null

Upvotes: 0

Views: 33

Answers (1)

vsfDawg
vsfDawg

Reputation: 1527

In the method studentid you define a local variable id. This hides the class instance variable id. The method returns the value that it calculates but it does not assign it to the instance variable.

You could alter this method to assign the calculated value into the instance variable

public int studentid(int grade) {
  int id =
  ... calcuation happens...
  this.id = id;
  return id;
}

Or, whomever is invoking this method can then set the value on the instance variable.

public void someMethod(int grade) {
  this.id = studentid(grade);
}

Upvotes: 1

Related Questions