Java auto increment issue - java

I'm having trouble with this requirement. I have this snippet:
private String id;
private int age;
private static int index;
public Customer(int a) {
this.id = a + "C" + index;
index++;
this.age = a;
}
It works fine. But the thing is, I want for every age the index will be reset to 1, like <10C1, 10C2> when there are 2 10-year-old customers and if you create a new customer with the age of 20 it will go back to <20C1,20C2,..>. Since there are no restriction to the age so the if statement seems not possible.

Use a static map in user:
private String id;
private int age;
private static map indexMap = new HashMap();
public Customer(int a) {
this.id = a + "C" + index;
index++;
this.age = a;
}
public synchronized static int getIndexOfAge(int age) {
if (!indexMap.contains(age)) {
indexMap.put(age, 1);
}
int theIndex = indexMap.get(age);
theIndex++;
indexMap.put(age, theIndex);
}
But I have to say this is really not a good way to code. You should use something like UserIndexFactory to create user index. You should also consider the thread safe and performance.

Related

How can I add Edit (Crud) functionality with Java?

I want to create add an edit functionality (public void EditPatientData()) to edit the patients surname, firstname,
dateOfBirth, Length and weight. In other words I want to be able to edit the Patient's in the system Id, Surname, firtstname etc.
import java.text.DecimalFormat;
import java.time.LocalDate;
import java.time.Period;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.Scanner;
public class Patient {
private static final int RETURN = 0;
private static final int SURNAME = 1;
private static final int FIRSTNAME = 2;
private static final int DATEOFBIRTH = 3;
private static final int LENGTH = 4;
private static final int WEIGHT = 5;
private static final int EDIT = 6;
private int id;
private String surname;
private String firstName;
private LocalDate dateOfBirth;
private double length;
private double weight;
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
public int getId() {
return id;
}
public String getSurname() {
return surname;
}
public String getFirstName() {
return firstName;
}
public LocalDate getDateOfBirth() {
return dateOfBirth;
}
public double getLength() {
return length;
}
public double getWeight() {
return weight;
}
// Method to calculate the age of a patient
public int calcAge(LocalDate dateOfBirth) {
//Code gets current date
LocalDate curDate = LocalDate.now();
//If else statement that checks if both dates are not null/
if ((dateOfBirth != null) && (curDate != null)) {
/*if dates are both not null the code will take the birthdate and currentdate and
calculate the difference the code will calculate the age in years */
return Period.between(dateOfBirth, curDate).getYears();
} else {
//if one or both dates are null the code will return 0
return 0;
}
}
//this code formats the double in 2 decimals so it looks cleaner
private static final DecimalFormat df = new DecimalFormat("0.00");
//this code calculates the BMI of the patient
public String calcBMI(double weight, double length) {
return df.format(weight / (length * length));
}
// Constructor
Patient(int id, String surname, String firstName, LocalDate dateOfBirth, double weight,
double length) {
this.id = id;
this.surname = surname;
this.firstName = firstName;
this.dateOfBirth = dateOfBirth;
this.weight = weight;
this.length = length;
}
// Display patient data.
public void viewData() {
System.out.format("===== Patient id=%d ==============================\n", id);
System.out.format("%-17s %s\n", "Surname:", surname);
System.out.format("%-17s %s\n", "firstName:", firstName);
System.out.format("%-17s %s\n", "Date of birth:", dateOfBirth);
System.out.format("%-17s %s\n", "Age:", calcAge(dateOfBirth));
System.out.format("%-17s %s\n", "Weight in KG:", weight);
System.out.format("%-17s %s\n", "Length in M:", length);
System.out.format("%-17s %s\n", "The Patients BMI:", calcBMI(weight, length));
}
// Shorthand for a Patient's full name1
public String fullName() {
return String.format("%s %s [%s]", firstName, surname, dateOfBirth.toString(),
calcAge(dateOfBirth), weight, length, calcBMI(weight, length));
}
//Edit patient data.
public void EditPatientData() {
}
}
What do you mean by add & edit?
If add mean you want to add a patient! Then you can use your Patient constructor to create(add) New Patient.
If you want to edit a Patient then you need to add a setters for your fields and use these setters to edit some values for your patient object.
Basically if you want to add 2 patients you will need an array. It is best practice that keep all your logic work methods in different classes rather than Patient- data class.
In this case, you will basically not need any getter or setter method. The constructor will be more than enough here.
Check methods and try to understand the logic.
We have basic few line codes that we have used them 2 3 times but every time it helped us do different things. For example, fillMethod() helps us in registration, also with updates. Always try to write code that you can use for many things.
I hope it will help
Step 1: Create one config and first add an array:
It will store patients' index. So when you want to update let's say, the 4th patient, you will call basically the 4th patient and you will update it.
public class Config {
//Patient's data
public static Patient[] patients= null;
}
Step 2: Create InputUtil class and add 3 main methods: registerPatients(), printRegisteredPatients() and updatePatients()
public class PatientUtil {
//this method for register
public static void registerPatients() {
//to set Config Patients array size. How
int numberOfPatients= //many patients you will register, write num
Config.patients= new Student[numberOfPatients];
for (int i = 0; i < count; i++) {
System.out.println((i + 1) + ".Register");//1. Register
//we put patient to the index
Config.patients[i] = PatientUtil.fillPatient();
}
System.out.println("Registration completed successfully!");
PatientUtil.printAllRegisteredPatirnts();
}
//Step 3. Create fillPatient() method to fill the patient
// this method will help us register and uptade time
public static Patient fillPatient() {
PAtient patient = new Patient(int id, String surname, String firstName,
LocalDate dateOfBirth, double weight,
double length);
return patient;
}
//Step4: Print all registered patients
public static void printAllRegisteredPatients() {
if (Config.patients== null) {
return;
}
for (int i = 0; i < Config.patients.length; i++) {
Patient pt = Config.patients[i];
System.out.println((i+1)+"."+pt.fullname());//this is your toString method
}
}
//Step5 Update Patients
public static Patient updatePatient(){
int updatePatientAtThisIndex = //write number that you want to update exact patient
System.out.println("Enter the details: ");
Patient updatingPatient = PatientUtil.fillPatient();// asking new student details
Config.patients[updatePatientAtThisIndex ]=updatingPatient ;//updating that index we asked before with new data
}
}

Create unique ID with constructor

I want to create objects with a name and a unique ID number that increments with the creation of each user.
class user {
static int uid = 0;
String name;
public user (String name){
User.uid = uid++;
this.name = name;
}
}
When creating user objects in a main method and printing out their ID they all return 0. I think there is a simply fix to this but can't seem to find it elsewhere online.
Your code has several problems:
A User doesn't have any ID. All you have is a static ID, thus shared by all users
You're incrementing the static ID, and then assigning its previous value to the ID right after.
You're not respecting the Java naming conventions.
The code should be
class User {
private static int uid = 0;
private String name;
private int id;
public User(String name) {
uid++;
this.id = uid;
this.name = name;
}
// getters
}
or, if you want the IDs to start at 0:
class User {
private static int uid = 0;
private String name;
private int id;
public User(String name) {
this.id = uid++;
this.name = name;
}
// getters
}

java constructor handling lack of arguments

i have this code here for a person details and the person should be intialized always whatever the number of possible arguments given ,like for example only height and age or salary and age
and i find it difficult to declare a constructor for every combination of arguments , is there a more optimal solution than that ??
class person {
public static final int defalut_salary=1000;
public static final int default_age=20;
public static final double default_height=6;
public static final String default_name="jack";
protected int salary;
protected int age;
protected double height;
protected String name;
person(){
}
}
I would suggest using the Builder pattern:
public final class Person {
private final int salary;
private final int age;
private final double height;
private final String name;
public Person(int salary, int age, double height, String name) {
this.salary = salary;
this.age = age;
this.height = height;
this.name = name;
}
// Getters or whatever you want
public static class Builder {
// Make each field default appropriately
private int salary = 1000;
private int age = 20;
private double height = 6;
private String name = "jack";
public Builder setSalary(int salary) {
this.salary = salary;
return this;
}
// Ditto for other properties
public Person build() {
return new Person(salary, age, height, name);
}
}
}
Usage:
Person person = new Person.Builder().setAge(25).setHeight(15).build();
You can perform validation in the Person constructor, and if you want to make any of the fields mandatory, you could take those in the Builder constructor.
Initialize all fields in a default constructor and use methods to set values in the desired fields, for example like this:
class A{
Field a;
Field b;
Field c;
public A(){
a = SOME_VALUE;
b = SOME_VALUE;
c = SOME_VALUE;
}
public A withA(Field a){ this.a = a; return this; }
public A withB(Field b){ this.b = b; return this; }
public A withC(Field c){ this.c = c; return this; }
/* other code */
}
Then you can use it like this:
A a = new A().withB(SOME_OTHER_VALUE).withC(YET_DIFFERENT_VALUE);
If don't want the fields' values to be changed with subsequent calls to withX() methods, you can use a full-fledged builder pattern.
You could define the constructor to take primitive wrapper classes (like java.lang.Integer or java.lang.Double) instead of primitives. The difference is that this allows you to pass null instead of a value. You can then check them for null. When they are null, you assign the default value. When they aren't, you assign their value.
public Person(Integer salary, Integer age, Double height, String name) {
if (salary == null) this.salary = salary else this.salary = default_salary;
if (age == null) this.age = age else this.age = default_age;
//...
}
The invocation new Person(1200, null, 5.3, null); would mean "create a person with start salary 1200, default age, height 5.3 and default name".
Another approach is to use the builder pattern as shown in the answer by Jon Skeet. It is less concise, but more readable.

how to have a unique student Id

The problem is that I cant create a unique Student number, Sometimes I get the same student Id when i store a student, is there anyway of generating unique studentID numbers, I need to amend the store method so its creating a unique
public class Collection
{
private ArrayList<Student> studentList;
public Collection()
{
studentList = new ArrayList<Student>();
}
public void storeStudent(Student student)
{
student.setId(createId("AB",9));
studentList.add(student);
}
public String createId(String pre, int number)
{
Random random = new Random();
int index = random.nextInt(number);
return pre + index + " ";
}
}
public class Student
{
private String studentId;
private String name;
public Student( String name)
{
studentId = "UnKnow";
this.name = name;
}
public void setId(String id)
{
studentId = id;
}
}
You could use a UUID:
public String createId() //don't need the arguments any more
{
UUID uuid = UUID.randomUUID();
return uuid.toString();
}
Extremely unlikely to ever have a clash.
make the studentId variable static and create static method to generate studentId.
private static studentId = 0;
...
public static int generateStudentId()
{
return studentId++;
}
you might also want to store this value to db or file or whatsoever, in case you stop the app and relaunch.
private static final AtomicInteger idIncrement = new AtomicInteger();
public static String createId(String pre /*, int number -- no longer needed*/)
{
int index = idIncrement.incrementAndGet();
return pre + index + " ";
}
This would give you thread-safe unique ordered student ids.
Try to use Set in collections. It will not allow duplicates. Also you can easily convert Set into List as follows.
List<T> list = new ArrayList<T>(set);
Brief tutorial on set.
Hope this will helpful to you.
Thanks you.
try
class Collection {
static long id = System.currentTimeMillis();
public void storeStudent(Student student) {
student.setId(++id + "");
studentList.add(student);
}
It guarantees unique IDs even after you restart the app. Note that it is not thread safe, if you need it to be thread-safe use AtomicLong id = new AtomicLong(System.currentTimeMillis).

Create a default constructor in Java

I need to create a method with a default constructor, which sets name to an empty string and sets both credits and contactHours to zero. How to do it? Thanks, Pieter.
Methods don't have constructors... classes do. For example:
public class Dummy
{
private int credits;
private int contactHours;
private String name;
public Dummy()
{
name = "";
credits = 0;
contactHours = 0;
}
// More stuff here, e.g. property accessors
}
You don't really have to set credits or contactHours, as the int type defaults to 0 for fields anyway.
You're likely to want at least one constructor which takes initial values - in which case your parameterless one can delegate to that:
public class Dummy
{
private String name;
private int credits;
private int contactHours;
public Dummy()
{
this("", 0, 0);
}
public Dummy(String name, int credits, int contactHours)
{
this.name = name;
this.credits = credits;
this.contactHours = contactHours;
}
// More stuff here, e.g. property accessors
}
public class Test {
private String name;
private int credits;
private int contactHours;
public Test {
this( "", 0, 0);
}
public Test (String name, int credits, int contactHours) {
this.name = name;
this.credits = credits;
this.contactHours = contactHours;
}
// more code here
}
public class Bibabu{
private String name;
private int credits;
private int contactHours;
public Bibabu(){
name = ""; // you could also write this.name and so on...
credits = 0;
contactHours= 0;
}
// more code here
}
You don't need a constructor:
public class Dummy
{
private int credits = 0;
private int contactHours=0;
private String name="";
/*
public Dummy()
{
name = "";
credits = 0;
contactHours = 0;
}
*/
// More stuff here, e.g. property accessors
}
//constructor
public Account(int id, double balance, Person owner){
this.id = id;
this.balance = balance;
this.owner = owner;

Categories

Resources