0

I am doing some coding in Java, but it doesn't work:

import java.util.Scanner;

import java.util.Arrays;

public class Main {

    public static void main(String[] args) 
    {
        Scanner input = new Scanner(System.in);

        String [] studentId = new String [3];

        Student name;

        for (int i = 0; i < 3; i++) 
        {
        System.out.print("Enter Name => ");
        name = new Student(input.next());
        studentId[i] = name.toString();
        }
        for (int i = 0; i < 3; i++) 
        {
        System.out.println(studentId[i]);
        }    
}
}
public class Student
{
    private static int studentId;
    private String name;

    public Student(String name) 
    {
    this.name=name;    
    setStudentId(studentId++);
    }

    public int getStudentId() 
    {
    return studentId;
    }

    public void setStudentId(int studentId) 
    {
    this.studentId = studentId;
    }

    @Override
    public String toString()
    {
        return (this.studentId +" "+ "student is "+ " " + "(" + this.studentId + ")"+ this.name);
    }
}

I need to auto-increment the Id when a new entry is created. I try everything but still cant increased it.

2 Answers2

1

You are using a static variable for everyone's Ids. You need a separate, non-static field to store each individual Id.

public class Student
{
    private static int nextAvailableStudentId = 1;
    private String name;
    private int studentId;

    public Student(String name) 
    {
    this.name=name;    
    setStudentId(nextAvailableStudentId++);
    }

    public int getStudentId() 
    {
    return studentId;
    }

    public void setStudentId(int studentId) 
    {
    this.studentId = studentId;
    }

    @Override
    public String toString()
    {
        return (this.studentId +" "+ "student is "+ " " + "(" + this.studentId + ")"+ this.name);
    }
}
Kevin
  • 7,162
  • 11
  • 46
  • 70
-1

In constructor it should be:

{
    public Student(String name) 
    {
        this.name=name;    
        setStudentId(studentId + 1);
    }
}
PhuLuong
  • 527
  • 4
  • 11
  • This won't fix the problem. He has the student Id as a static variable. This will just change it from all the students having studentId 0 to all the students having studentId 3 – Kevin Apr 03 '20 at 20:39
  • HI @Kevin, Did you try my code? Give me one up vote if I'm right. Thanks – PhuLuong Apr 04 '20 at 01:23
  • It only "works" because he is calling to string on it immediately after creating it. If he waited and called string on each object after he had instantiated them all, you would see that all the studentIds are the same. I've demonstrated here: https://onlinegdb.com/Sylr3PIvI – Kevin Apr 04 '20 at 20:24