Reputation:
Im having an issue where I have to create a method in java to get a ticket number which every time it is called it generates a number sequentially.
this is what I have so far regarding the ticket method
public class Ticket
{
public static final String PREFIX = "CAR";
public static int number = 1000;
//instance variables
private String ticketNumber;
public Ticket(){
ticketNumber = generateTicketNumber();
}
public String getTicketNumber(){
return ticketNumber;
}
private String generateTicketNumber(){
number = number++;
ticketNumber = PREFIX +number;
return ticketNumber;
}
I'm told to use a static variable (which i have) to create and hold a counter to generate part of the ticket number, increment the static variable and assign it combined with the string prefix to the field ticketNumber. When i create an object it does not increment to CAR1001, it just goes CAR1000, am I to try a while loop for this?
Upvotes: 0
Views: 674
Reputation: 51112
number = number++;
is not evaluated how you think. What this actually does is that the right-hand side increments number
, but number++
is also an expression whose value is the old value of number
, before the increment is done. Then because of the number = ...
assignment, that old value is assigned to number
on the left-hand side, undoing the increment.
So you should just write number++;
instead, which simply increments the variable.
Upvotes: 3
Reputation: 201497
Unless I'm missing something, I think you've over complicated this. All you need is PREFIX
and number
. Concatenate PREFIX
with number
and increment number
. That can be done in one step like,
public class Ticket {
private static final String PREFIX = "CAR";
private static int number = 1000;
public String getTicketNumber() {
return PREFIX + number++;
}
}
Or, perhaps a little easier to read,
public String getTicketNumber() {
try {
return PREFIX + number;
} finally {
number++;
}
}
Upvotes: 1