create Unique id in a private method createaccountID() without using the uuid - java

The private createAccountID() method should create a new unique id everytime an Account is created i.e. the first account created will have the ID
“A1000”. The account ID will increase by 1 for each new account, i.e. the second
will have ID “A1001” etc. and there shouldnt be any duplicates.
I am not really sure how to start this method, except that i created a static variable called counter that is set to 0. I think i have to use a .equals() method or something to make sure that the first isn't equal to the new one else it will print an error messege like ("Duplicate")
I am also not sure whether to go with public void createAccountID() or
public String createAccountID()
Here is the code:
public class Account
{
private Customer customer;
private String accountID;
private double balance;
private static int counter = 0;
private static final double OPENING_BALANCE = 0.0;
public Account()
{
setCustomer(new Customer());
setBalance(OPENING_BALANCE);
createAccountID();
}
public Account(Customer theCustomer, double theBalance)
{
setCustomer(theCustomer);
setBalance(theBalance);
createAccountID();
}
private void createAccountID()<------------------------------------------------
{
accountID = "A";
for(counter = 0; counter >= 0; ++counter){
accountID+=counter;//stuck in loop doesnt work.
//just thought id try it
}
}
public void setCustomer(Customer theCustomer)
{
if(theCustomer == null){
customer = new Customer();
}
else{
customer = theCustomer;
}
}
public Customer getCustomer()
{
return customer;
}
public void setBalance(double theBalance)
{
if(theBalance <= OPENING_BALANCE){
System.out.println("Error. No Negative values");
}
else{
balance = theBalance;
}
}
public double getBalance()
{
return balance;
}
}
Any help appreciated Cheers

You can set your 'counter' starting value to 1000 and concatenate it to 'A' char to set in 'accountID'.
To make sure, that there is no duplicates, you can use a Set interface. For example, a HashSet implementation in a private static field.
Another variant is to use a TreeSet and use its last() method to obtain the latest ID. Then you can avoid using a counter. For instance, you can store a starting counter with value '1000' and increment it with treeSet.last() and then store the result.
Also, I`m not sure why do you need a public createAccountID(). This is something, that should be incapsulated inside your class and should not be invoked externally.
Maybe it makes sense to change your accountID field to int and concatenate to 'A' in a getter method.
//
Or maybe you just need a static counter with a starting value '1000' and then call in constructor:
this.accountID = 'A' + counter++;

If there aren't multiple threads involved, using the static counter will ensure that there aren't duplicates.
In case of multiple threads, you could use an AtomicInteger. In this case, make sure that first you increment the AtomicInteger with incrementAndGet(1) and after you create the ID:
private static final AtomicInteger counter = new AtomicInteger(1000);
private static final String PREFIX = "A";
private String accountID;
private void createID() {
final int number = counter.incrementAndGet(1);
accountID = PREFIX + number;
}
Note that the createID method should be private, as stated by #Michael Cheremukhin.

Create a static variable counter, concatenate it to A and increment it. Keep your function private, you shouldn't call it from outside your class.
private void createAccountID()
{
accountID = "A" + counter++;
}

Related

Two instance variables in the class of a one dimensional array

I'm hoping someone can help me out with a question that I've been stuck on for quite a while.
Just to clarify the scenario. There is a show being held in a theatre that can hold 180 people. They allow online bookings that are written to a text file "bookings.txt" Individual bookings are single that only have a seat, contact and payment status record. Whereas group bookings have seats, a contact number, payment status, group name and group size records.
So far I have created the Bookings and GroupBookings classes. I'll show them below:
/**
*
* #author OP
*/
public class Booking
{
public String seat;
public String contact;
public double cost;
public boolean paid;
//Constructor
public Booking(String st, String ct, int cost, boolean pd)
{
seat = st;
contact = ct;
this.cost = cost;
paid = pd;
}//end of Booking
//Getters
public String getSeat()
{
return seat;
}//end of getSeat
public String getContact()
{
return contact;
}//end of getContact
public boolean isPaid()
{
return paid;
}//end of isPaid
public double getCost()
{
//Determining what discount should be applied to their seat location
if (seat.contains("A") || seat.contains("B") ||
seat.contains("C") || seat.contains("D"))
{
cost = 200;
}
else
{
if (seat.contains("E") || seat.contains("F") ||
seat.contains("G") || seat.contains("H"))
{
cost = 160;
}
else
{
if (seat.contains("I") || seat.contains("J") ||
seat.contains("K") || seat.contains("L"))
{
cost = 120;
}
}
}//end of nested if statement
return cost;
}//end of getCost
#Override
public String toString()
{
return seat + "\t" + "R" + cost + "\t" + paid;
}//end of toString
}//end of class booking
/**
*
* #author OP
*/
public class GroupBooking extends Booking
{
private String groupName;
private int groupSize;
public GroupBooking(String st, String ct, boolean pd, String gn, int gs)
{
//Variables from previous class (using inheritance)
super.seat = st;
super.contact = ct;
super.paid = pd;
//New variables for this class
groupName = gn;
groupSize = gs;
}//end of GroupBooking
#Override
public double getCost()
{
cost = super.getCost();
for (int i = 0; groupSize % 4 > i; i++)
{
cost = cost - 60;
i++;
}//end of for loop
return cost;
}//end of getCost
public int getGroupSize()
{
return groupSize;
}//end of getGroupSize
public String getGroupName()
{
return groupName;
}//end of getGroupName
#Override
public String toString()
{
return seat + "\t" + "R" + cost + "\t" + groupName;
}//end of toString
}//end of class GroupBooking
Now for the question that I am stuck on:
A new class has to be created called BookingManager. From there I have to declare two instance variables in the class of one-dimensional array that can be used to store up to 180 Booking or GroupBooking objects. An integer counter must also be created to keep track of how many Bookings are stored in the array. (These two instance variables should not be accessible from outside the class)
I'm still a newbie in coding and I'm unsure of what to do here. The follow-up question is also giving me difficulties:
A contractor then has to be created to read the information from the text file "bookings.txt". Each line either contains a single Booking or a GroupBooking object. Read each line from the file and instantiate the appropriate type of object (Booking or GroupBooking) and add it to the array. (Note in the case of GroupBooking you must create an object in the array for each member of the group. Exp for a group of six you have to have six separate GroupBooking objects in the array.)
I know a file scanner is needed from the second question but I have no idea whether to use a for loop or an if statement to differentiate between a single booking or a group booking.
If anyone can help I would truly appreciate it. This topic is still very new to me.
To prevent a variable being accessible outside a class declare the variable "private". e.g.
private String costtotal="";
An instance variable "is not" static ("is not" a class member variable), and are a global variable only declared at the top of the class code below the import statements, so exist until the class exits.
In your manager class you need a global variable array Booking class
Booking[] bookings;
private String costtotal=""; // e.g.
// in the constructor read the bookings file and find the number of bookings made
//int totalbooked=...whatever reading the file data counts to of bookings made;
bookings=new Booking[totalbooked];
// create and fill each Booking object and assign it to its index on the array in a loop
bookings[loopcount]=new Booking(st,ct,cost,pd);
Different schemes of class systematics of coding
// bean syntax in a java bean framework class type
public void setCosttotal(String costtotal){
this.costtotal=costtotal;
}
//bean syntax
public String getCosttotal(){
return costtotal;
}
// normal non bean syntax 1
public String costTotal(String csttot){
return (String)csttot;
}
// somewhere else in code in scope to global variable
costtotal=costTotal(valuein);
// normal non bean syntax 2
public String costTotal(String csttot){
costtotal=csttot;
return costtotal;
}

Can we use Setter Method in java to perform operations?

Is setter method only use to assigning values? or can we perform operations in it. Here in this code the commented part is giving me correct output but while using set and get I am getting output as 0.
I want to avoid calling totalMarksOfStudent() method again and again because it have 5 parameters which I dont want to give again and again. So what is the way to return totalMarksStudent in another class without calling totalMarksOfStudent().
int totalMarksStudent = 0;
public void setMarks(int englishMarks, int mathsMarks, int physicsMarks, int chemistryMarks, int csMarks) {
totalMarksStudent = englishMarks + mathsMarks + physicsMarks + chemistryMarks + csMarks;
}
public int getMarks(){
return totalMarksStudent;
}
// public int totalMarksOfStudent(int englishMarks, int mathsMarks, int physicsMarks, int chemistryMarks, int csMarks) {
// totalMarksStudent = englishMarks + mathsMarks + physicsMarks + chemistryMarks + csMarks;
// return totalMarksStudent;
}
public String displayTotalMarks() {
String totalMarks1 = "Name " + name + "\tRoll No " + rollNo + "\tTotal Marks " + getMarks();//totalMarksOfStudent(englishMarks, mathsMarks, physicsMarks, chemistryMarks, csMarks);
return totalMarks1;
}
Better to avoid that...
I think it's better to have some fields like your parameters in setMarks (englishMarks , mathsMarks , ...) , and give value to them in constructor or setter methods. Also it's better to have a method named something like calculateTotalMarks , and call it without any parameters whenever you need it. Remember that there will be no problem to have operations in setter methods but usually and for better designed program we avoid that. Methods should do the thing their name says : for example , setter just for assigning , getter just for accessing values , calculateTotalMarks for calculating the total marks and so on ...
setter method is usually used to assigning values. It is promise.
You can reduce parameters by using Object
I recommend to make object of MarksStudent. because common attribute can bind to one class. It make understand easily code
for example
// Java is object-oriented language
class marksStudents {
private int english;
private int math;
private int physics;
private int chemistry;
private int cs;
//getMethods is Abbreviation
public int getTotal() {
return english+math+physics+chemistry+cs;
}
//setMethods
public void setEnglish(int english) {
this.english = english;
}
public void setMath(int math) {
this.math = math;
}
public void setPhysics(int physics) {
this.physics = physics;
}
public void setChemistry(int chemistry) {
this.chemistry = chemistry;
}
public void setCs(int cs) {
this.cs = cs;
}
}
To execute
public class Main{
public static void main(String[] args) {
// You can make object marksStudents of studentsA
marksStudents studentsA = new marksStudents();
studentsA.setChemistry(20);
studentsA.setEnglish(30);
studentsA.setMath(40);
studentsA.setCs(50);
studentsA.setPhysics(60);
//200
System.out.println(studentsA.getTotal());
// You can make object marksStudents of studentsB too
marksStudents studentsB = new marksStudents();
studentsB.setChemistry(10);
studentsB.setEnglish(10);
studentsB.setMath(10);
studentsB.setCs(10);
studentsB.setPhysics(10);
//50
System.out.println(studentsB.getTotal());
}
}
The getter/setter method is only a practice. Not bad practice - it just defines a class, whose instances for the external world are handled by a list of independent values. Using them makes your code better comprehensible and easy to understand, what is it doing.
So it is no problem to make other operations with it, in general.
Some frameworks like to use reflection to use getters/setters and also reach the variables directly in them. In these cases, doing any different in the getters/setters than reading/writing the private members is no wise idea. Sometimes you can use a little bit of api/impl interface trickery to handle this problem.

How to add a Course object to an array via an addCourse() method

I am having issues with objects and classes.
I had to define two classes:
Course: a course has a code, an name and a number of credits
Teacher: a teacher has a first name and last name. He can be asked his full name.
So far so good, I got no issue with them, but I have to do next assignment which I was trying to do in the last 2 days and I could not find a proper answer:
Extend the code of the class teacher. A teacher also has a list of courses he can teach. Add an array of Courses to the code. Also add a function addCourse(Course aCourse) to the code. Courses can also be removed from teachers.
I could do everyting in my way but no clue on how to create the addCourse(Course aCourse) method.
Find below my coding, but it must be according to the method described:
public class Course {
private String courseCode;
private String courseName;
private String numberOfCredits;
public Course(String courseCode, String courseName, String numberOfCredits) {
super();
this.courseCode = courseCode;
this.courseName = courseName;
this.numberOfCredits = numberOfCredits;
}
public void print() {
System.out.println(courseCode + "\t" + courseName + "\t" + numberOfCredits);
}
public static void main(String[] args) {
Course[] courseArray = new Course[4];
System.out.println("Code" + "\t" + "Name" + "\t" + "Credits");
courseArray[0] = new Course("001", "Hist", "3");
courseArray[1] = new Course("002", "Phy", "3");
courseArray[2] = new Course("003", "Math", "3");
courseArray[3] = new Course("004", "Log", "3");
for (int i = 0; i < courseArray.length; i++) {
courseArray[i].print();
}
}
}
Arrays are fixed length collections of objects, so you'll need to decide how big your array should be. Let's call the length of your array MAX_COURSES. A more advanced solution might resize the array when required, but I get the impression this is beyond the scope of your course.
So you need to define the Course[] array as a field of your Teacher class. The syntax of array declarations is quite easy to research, so I won't put that in here. Just make sure your array length is equal to MAX_COURSES.
Now, to add courses to the array, you need to know where to put them. To keep track of the next free position of the array, the easiest thing to do is to declare a field in your class:
private int numCourses = 0;
Now, when you add a new course, insert the course into the index specified by numCourses. Make sure you increment numCourses after you've added the course.
Finally, you ought to test to see if your array is full before you agree to insert a new course into the array, i.e. check if numCourses is smaller than MAX_COURSES. If it's not, you need to throw an exception.
I would recommend using a collection (such as a List) rather than an array. The code would look something like:
public class Teacher {
private final String firstName;
private final String lastName;
private final List<Course> courses = new ArrayList<Course>();
public Teacher(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
public void addCourse(Course course) {
courses.add(course);
}
}
Based on that example, you should be able to add the removeCourse method yourself, and any other method you need to operate on the list of courses.
If you want to return the list as an array, you could always convert it, e.g:
public Course[] getCourses() {
return courses.toArray(new Course[courses.size()]);
}
If you really need to use an array for the data structure based on your assignment, something you can try when adding and removing courses, is to construct a list from the array of courses, add or remove a course from that list, the convert the list back to an array of courses.
There's really 3 options here.
Option 1
If you're allowed to use List constructs:
private List<Course> courses = new ArrayList<Course>();
public void addCourse(Course aCourse)
{
if (aCourse == null)
{
return;
}
courses.add(aCourse);
}
Option 2
The uses arrays, but it doesn't scale. Assume that a teacher can only have a maximum of X courses, in my example 10:
// Yes, I stole Duncan's variable names
private final int MAX_COURSES = 10;
private int numCourses = 0;
private Course[] courses = new Course[MAX_COURSES];
public void addCourse(Course aCourse) {
if (aCourse == null)
{
return;
}
if (numCourses >= courses.length)
{
return;
}
courses[numCourses] = aCourse;
numCourses++;
}
Option 3
This is identical to the previous item, but is a bit smarter in that it can resize the array... by creating a new one using the static method Arrays.copyOf
// Yes, I stole Duncan's variable names
private final int MAX_COURSES = 10;
private int numCourses = 0;
private Course[] courses = new Course[MAX_COURSES];
public void addCourse(Course aCourse) {
if (aCourse == null)
{
return;
}
if (numCourses >= courses.length)
{
int size = courses.length * 2;
courses = Arrays.copyOf(courses, size);
}
courses[numCourses] = aCourse;
numCourses++;
}

How can I print out an arraylist and also How can I add errors checks to the arraylist?

I have been trying to solve this problem for ages and with no luck I didn't progress. Could someone please help me out. I have created an arrayList, made an getter class, have made a method. I can add stuff to the array list as well but when I print the arrayList out it prints out some random text.
below is the arrayList I created.
public static ArrayList<getArrayList> arrayList = new ArrayList<getArrayList>();
here is my method;
private static void addToArrayList(String a, double no1, int no2, int no3) {
try {
arrayList.add(new getArrayList(a, no1, no2, no3));
} catch (Exception e) {
e.printStackTrace();
}
}
here is my getter class
public class getArrayList {
private String name;
private double seconds;
private int speed1;
private int speed2;
public String getName() {
return name;
}
public double getSeconds() {
return seconds;
}
public int getSpeed1() {
return speed1;
}
public int getSpeed2() {
return Speed2;
}
public StoreCommands(String storeName, double storeSeconds, int storeSpeed1, int storeSpeed2) throws Exception{
name = storeName;
seconds = storeSeconds;
speed1 = storeSpeed1;
speed2 = storeSpeed2;
}
}
to add stuff on this list I use the method I created
addToArrayList(String a, double no1, int no2, int no3) filled in with my values
and to receive stuff from the arraylist I use this
for(getArrayList s : arrayList) {
System.out.println(arrayList + "\n")
;
and it prints out if i use System.out.println(arrayList), depending on how much I add to the arraylist.
[StoreCommands#49a21b63]
Besides that could someone tell me how I can set a size of the arrayList so if anything more that is being added it won't add and give an error.
Also I need to perform certain error checks once the items are in the arrayList
*1st If the an item is added to the list and the user tries to add the same one again straight after I want to display an error.. (the user can add the same stuff but not directly after the one they just added, they will need to add something else first)
*2nd if say user wants to add apples to the list, I want to limit that to only 2 time in the whole list, more than that will not be added and will display and error.
Could someone help me out please, I will really appreciate it.
Thanks.
Try this -
for(getArrayList s : arrayList)
System.out.println(s + "\n");//This print the tostring of getArrayList class
Again override the toString method of getArrayList class, to print actual field value of the object. Example -
public class getArrayList {
public String toString(){
return name +"||" +seconds+"||"+ speed1+"||"+speed2;
}
}
Note : Follow java nomenclature standard, first later of you class name would be capital And also give a relevent name to the Class.
Overriding toString method will help you to print actual data. Override it in your class getArrayList. One more thing is class name should start with capital letter.
public String toString()
{
return "Name : "+name+" Seconds : "+seconds+" Speed1 : "+speed1+" Speed2 : "+speed2;
}
and use it like
for(getArrayList s : arrayList)
System.out.println(s.toString);
You can limit the size by adding check to
private static void addToArrayList(String a, double no1, int no2, int no3) {
try
{
if(arrayList.size < 10) //any size you want
arrayList.add(new getArrayList(a, no1, no2, no3));
else
System.out.println("ArrayList is full");
} catch (Exception e) {
e.printStackTrace();
}
}
You don't have to loop in order to print an array, just do:
System.out.println(Arrays.toString(arrayList.toArray()));
ArrayList doesn't have a mechanism to limit the size, if you want to do it - you'll have to implement it.
Example:
import java.util.ArrayList;
/**
* User: alfasin
* Date: 2/5/14
*/
public class RestrictedSizeArrayList<E> extends ArrayList<E> {
private static final int limit = 6;//example
#Override
public boolean add(E e){
if(this.size() > 5){
throw new IndexOutOfBoundsException("Can't add more than 5 elements to the ArrayList");
}
boolean result = super.add(e);
return result;
}
}

TreeSets and removing specific unnamed Objects

So I'm writing a program for an assignment where I store Patients into a TreeSet. The problemn I'm having is I have to implement a method to discharge a specefic patient from the TreeSet.
for(int i = 0; i < 10 ; i++){
Random ag = new Random();
int age = ag.nextInt(99) + 1;
Names randomname = Names.getRandom();
String name = randomname.name();
String sex;
if(Math.random() > 0.5)sex = "female";
else sex = "male";
Random sn = new Random();
int serial = sn.nextInt(10000) + 1;
Address randomAddress = Address.getRandom();
String address = randomAddress.name();
Hospital.admitPatient(new Patient(age, name, sex, serial, Birthday.produceBirthday(), address));
}
So Thats how I am looping to get the Patients info and stats for the Patient Object. The admit patient method adds them to the TreeSet.
public static void admitPatient(Patient obj){
if(numofPatients < maxPatients){
patientList1.add(obj);
}
}
The Problem I'm having is withbthe Discharge patient method. Where I don't know what to put in the method
public static void dischargePatient(What do i put here in the driver when i call this method?){
patientList1.remove(w/e i put up there);
}
Since I didn't name the Objects of patients when creating them but just inserted them straight into the TreeSet I'm not sure exactly how to call them when i call the discharge patient method.
As you usually want to work with selected objects (patients) and not the whole list, you need a way to identify them somehow (for example by name or ID).
Since add and remove are similar, your dischargePatient method will be similar as well. Try
public static void dischargePatient(Patient patient) {
patientList1.remove(patient);
}
To retrieve a patient with a certain ID, you may iterate through your set and return it:
public Patient getPatientByID(String id) {
for (Patient patient : patientList1) {
if (patient.getID().equals(id)) {
return patient;
}
}
}
To remove a patient with ID "1234abc", you could do the following:
dischargePatient(getPatientByID("1234abc"));
Using this pattern, you rebuild the functionality of the map datastructure. Thus it might be better to use a Map (e.g. HashMap<>). Code will be reduced to operations like:
Map<String, Patient> patients = new HashMap<>();
patients.put("1234abc", patient1);
patients.remove("1234abc");
Full code for your example:
public static void admitPatient(Patient patient) {
if(numofPatients < maxPatients){
patients.put(patient.getID(), patient);
}
}
public static void dischargePatient(String id) {
patients.remove(id);
}

Categories

Resources