Search code examples
javaincrementauto-increment

Auto increment for transaction number (Eclipse Java)


I want to get increasing value starting with 1 so that I get TK-1 all the way to TK-n.

What I've tried is:

public class Main {
addTicket();


public void addTicket() {
int a;
String ticket;
a = getA();
ticket = "TK-"+ a
System.out.println(ticket)
}

public int getA() {
    int a, b;
    a = 0;
    b = a++;
    return a;
public static void main(String[] args) {
    new Main();

}
}

Sorry it's my first time learning to code, can someone explain to me why it isn't working and what should I do to make it work ?

Thanks in advance.


Solution

  • If you need an autoincrease ID, you need a static int:

    public class Ticket {
        static int ticketID = 1;
    
    
        public void addTicket() {
            int a;
            String ticket;
            a = getticketID();
            ticket = "TK-" + a;
            System.out.println(ticket);
        }
        public int getticketID () {
            return ticketID++;
        }
    
        public static void main(String[] args) {
            Ticket test  = new Ticket();
            test.addTicket();
            test.addTicket();
            test.addTicket();
    
        }
    }
    

    output:

    enter image description here