Reputation: 11
I am currently building a mock Hospital administration system. I have successfully been able to write user registration inputs such as name, gender etc. from jTextFields into a text file but I am struggling with the idea of making an auto incrementing unique identifier that changes with each new line of the text file. I have a jTextField dedicated towards it but have been unsuccessful in making the int variable increase by 1 each time the Add record button is clicked.
I have declared "reg" as an integer equal to 1
int reg = 1;
Because I need to send the number to a text file I convert it to a string and set the uneditable textfield regnumber to that string before it writes to the text file
String regString = Integer.toString(reg);
regnumber.setText(regString);
Unfortunately reg continues to appear as 2 when it gets written to the file. How and at what point to I use the ++ operator to increase reg number in the texfield every time the frame is loaded. Any help would be much appreciated
Upvotes: 1
Views: 9106
Reputation: 338181
You have not included enough detail in your Question to know for sure what the issue is, but here is my guess.
++
& --
, meaning on the right-side of a variable, take effect after the value from the variable is accessed.See the demo in the Java Tutorials by Oracle. I suggest you take time to study these tutorials, as they cover all the basics of learning Java.
// prints 5
System.out.println(i);
// prints 6
System.out.println(++i);
// prints 6
System.out.println(i++);
// prints 7
System.out.println(i);
Upvotes: 1
Reputation: 3540
Read the value from the file only once and initialize it to an AtomicInteger. Use incrementAndGet()
method to increment and obtain the current value by one.
private static AtomicInteger at = new AtomicInteger(0);
public int getNextCountValue() {
return at.incrementAndGet();
}
I hope it helps.
Upvotes: 1