-2

i created an Arraylist of Student objects. i am using a static variable as an ID.

this is what my Student class looks like;


Student class


And the Runner file looks like;

Runner file



the output i receive is;

St_ID St_Name St_Age St_Course 3 James 23 Statistics 3 Mick 24 Biology 3 Jenni 22 Literature

but what i require is;

St_ID St_Name St_Age St_Course 1 James 23 Statistics 2 Mick 24 Biology 3 Jenni 22 Literature

ThivankaW
  • 511
  • 1
  • 8
  • 21
  • 1
    Don't use a static value - or, reassign the running value to a non-static variable, so you would have a "generator" which would generate the next value, but that value need to be assigned to an instance field of your class – MadProgrammer Jan 07 '18 at 05:30
  • 1
    Please do NOT post pictures of code, include the code directly. Please visit the [help] and read [ask]. – Jim Garrison Jan 07 '18 at 05:30
  • 1
    Follow the link https://stackoverflow.com/questions/17547360/create-an-arraylist-of-unique-values – Kedar Km Jan 07 '18 at 05:44
  • Do the ids have to be starting from 1 and counting up? Because if you call hashcode() on your student class instances it will give you a unique number to identify your students by. – Meepo Jan 07 '18 at 06:00

2 Answers2

1

You are right about the count variable being static. However, the Student class should also have a field that stores the id of each student. This should be non-static since each student is going to have a different one.

private int id;

In the constructor, assign count to it:

count++;
id = count;

The getId method should be non-static and return id:

public int getId() { return id; }
Sweeper
  • 213,210
  • 22
  • 193
  • 313
0

If all you cant is a unique id, calling stobj.hashCode() will return a unique hashcode, so each student has a unique id. However, if you need the ids to start at 1 and count up, then keep the count, but also make a non-static variable and set it equal to the current count in the constructor.

public class Student {
    //fields here
    private static int count = 0; //not good style, but whatever
    private int id;

    public Student(String n, int a, String c) //you should work on your variable names
        count++;
        id = count;
        //other stuff here
Meepo
  • 368
  • 4
  • 19