Generate sequential number in java

Asked

Viewed 5,821 times

-1

Hello, I have a Student class with the attributes name and enrollment. The user can enter the name by setNome(), but I would like to know how to make the registration is generated automatically (1, 2 , 3, ...)

  • You’re saving it in a database?

  • @Maiconcarraro Não

1 answer

1


Creates a class that will hold the value static and that will always return you the value with increment, example:

Geradormatricula.java

public class GeradorMatricula {
    private static int ID = 1;

    public static int getProximaMatricula() {
        return ID++;
    }
}

Using

public static void main(String[] argv) {
    System.out.println(GeradorMatricula.getProximaMatricula());
    System.out.println(GeradorMatricula.getProximaMatricula());
}

Exit

1

2

  • The ID should be initialized with zero.

  • Actually not @ramaral, it would take zero only if I returned ++ID instead of ID++.

  • You’re right, I’m sorry, my distraction.

  • @We’re here to help you, don’t worry :)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.