How can I add Edit (Crud) functionality with Java? - 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
}
}

Related

How to write a method that reads particular content in an array lists and count the number of array's content

I am a new learner and I should create a method that will make this program work with no problems at all so I can get the :::final result that should look like this:::
3 is 3
Mark is Mark
Richard is Richard
Here is the code (PLEASE read the comments I wrote in the code)
public class Main {
/*I wrote the following method (Student) but I keep get some issues:
Please help I spend many days and I can't figure it out and I am runnung out
of time as I should understand the problem or at least the correction that I
can read and figure out what I was doing wrong.*/
// My written code starts here
public static String Student(String[] sx){
int counter = 0;
for (int i = 0; i < sx.length; i ++){
if (sx[i] != null) counter ++;
}
return counter;
sx = new String[counter];
}
// My written code ENDS here
// From this point I should preserve the code without any changes
static Student studentA;
static Student studentB;
static Student studentC;
public static void main(String[] args) {
studentA = new Student("Mark", "John", "Jimmy");
studentB = new Student("Will", "George", "Androw");
studentC = new Student("Frank", "Sam");
int totalStudents = Student.getTotalStudents();
System.out.println(totalStudents + " is 3");
System.out.println(studentA.getFirstName() + " is Mark");
studentA.setFirstName("Richard");
System.out.println(studentA.getFirstName() + " is Richard");
}
}
Check the following code snippet
import java.util.List;
public class Main {
// My written code starts here
static class Student {
String firstName;
String middleName;
String lastName;
// Constructor for setting the class variable with all 3 field
public Student(String firstName, String middleName, String lastName) {
this.firstName = firstName;
this.middleName = middleName;
this.lastName = lastName;
}
// Constructor for setting the class variable with 2 field
public Student(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
//to get the FirstName field of a student object
public String getFirstName() {
return firstName;
}
//to set the FirstName field of a student object
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public static int getTotalStudents() {
// this is wrong way of doing this.
// You should ideally send a list Of Student to know the number of students as shown below
return 3;
}
public static int getTotalStudentsFromList(List<Student> studentList) {
return studentList.size();
}
}
// My written code ENDS here
// From this point I should preserve the code without any changes
static Student studentA;
static Student studentB;
static Student studentC;
public static void main(String[] args) {
studentA = new Student("Mark", "John", "Jimmy");
studentB = new Student("Will", "George", "Androw");
studentC = new Student("Frank", "Sam");
int totalStudents = Student.getTotalStudents();
System.out.println(totalStudents + " is 3");
System.out.println(studentA.getFirstName() + " is Mark");
studentA.setFirstName("Richard");
System.out.println(studentA.getFirstName() + " is Richard");
}
}
I have added possible comments to explain the code. Let me know if you feel any difficulty in understanding this.

How to create an Arraylist with an object inside a class in java

The exercise is to have a class named Tenant that will be used to store values of tenants for an apartment. In the main class Prog2 I am trying to create an ArrayList that can hold 4 different values, all regarding the tenant class, which are - the tenant's name, apartment number, initial first payment, and monthly payment. I want to be able to print these values out in separate lines that will provide all 4 pieces of information per tenant - followed by a blank line, and then the same 4 pieces of information for another tenant if there is another one. I can get the program to prompt the questions correctly, but then all I get are nulls and 0's printed out (see below at comment). I appreciate all the help - I'm not the best at this.
// this class is the tenant class that passes all the tenant's
information
public class Tenant {
private String firstName;
private String lastName;
private String aptNumber;
private double yearlyRent;
private String fullName;
private double firstPayment;
private double monthlyPayment;
public Tenant(String name, String aptNum, double fPayment, double
mPayment){
name = fullName;
aptNum = aptNumber;
fPayment = firstPayment;
mPayment= monthlyPayment;
}
public Tenant() {
}
public void setFirstName(String name) {
firstName = name;
}
public void setLastName(String lName) {
lastName= lName;
}
public void setAptNumber(String apt) {
aptNumber = apt;
}
public void setRent(double rent) {
yearlyRent = rent;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public String getAptNumber() {
return aptNumber;
}
public double getRent() {
return yearlyRent;
}
public double getFirstPayment() {
double monthlyRent = yearlyRent/12;
firstPayment = monthlyRent * 3;
return firstPayment;
}
public double getmonthlyPayment() {
double firstAndLast = yearlyRent/12;
monthlyPayment = (yearlyRent - firstAndLast)/11;
return monthlyPayment;
}
public String getFullName(){
fullName = firstName + " " + lastName;
return fullName;
}
}
// The below class contains the main method
public class Prog2 {
public static double getDouble(Scanner scan) {
System.out.println("Enter yearly rent:");
while (!scan.hasNextDouble()) {
scan.next();
System.out.println("Error: please enter a numeric
value");
}
return scan.nextDouble();
}
public static void main(String[] args) {
Tenant tnt = new Tenant();
Scanner scan = new Scanner(System.in);
System.out.println("Enter number of tenenats:");
int numTenants = scan.nextInt();
ArrayList<Tenant> list = new ArrayList<Tenant>();
for (int i = 0; i<numTenants; i++) {
System.out.println("Enter first name:");
tnt.setFirstName(scan.next());
System.out.println("Enter last name:");
tnt.setLastName(scan.next());
System.out.println("Enter apt number:");
tnt.setAptNumber(scan.next());
tnt.setRent(getDouble(scan));
list.add(new Tenant(tnt.getFullName(), tnt.getAptNumber(),
tnt.getFirstPayment(), tnt.getmonthlyPayment()));
}
for (int i = 0; i < list.size(); i++) {
System.out.println(list.get(i).getFullName());
System.out.println(list.get(i).getAptNumber());
System.out.println(list.get(i).getFirstPayment());
System.out.println(list.get(i).getmonthlyPayment());
System.out.println();
}
}
}
// this prints out:
null null
null
0.0
0.0
null null
null
0.0
0.0
The issue is with the first constructor in the Tenant class. Remember that the = operator assigns the value of the right operand to the variable in the left operand. In your case the code should look like this:
public Tenant(
String name,
String aptNum,
double fPayment,
double mPayment)
{
fullName = name;
aptNumber = aptNum;
firstPayment = fPayment;
monthlyPayment = mPayment;
}
What I typically do with constructors is name the parameters after the field, then on the left side of the field assignments use this to refer to the field as opposed to the parameter. This ends up looking much clearer:
public Tenant(
String fullName,
String aptNumber,
double firstPayment,
double monthlyPayment)
{
this.fullName = fullname;
this.aptNumber = aptNumber;
this.firstPayment = firstPayment;
this.monthlyPayment = monthlyPayment;
}
this can be tricky to use but this is an example where it can clear things up.
Many things are wrong with your code .
Constructor of
public Tenant(String name, String aptNum, double fPayment, double
mPayment){
name = fullName;
aptNum = aptNumber;
fPayment = firstPayment;
mPayment= monthlyPayment;
}
here your not just assigning null values to your function parameeters, instead of assigning values to your class fields from function parameters.
Also, when you are calling function getFullName() , it will return null as firstName and lastName fields are not initialized.
So, you need to modify your constructor to -
public Tenant(String firstNamename, String lastName, String aptNum, double fPayment, double
mPayment){
this.firstName = firstNamename;
this.lastName = lastName;
this.aptNumber = aptNum;
this.firstPayment = fPayment;
this.monthlyPayment = mPayment;
this.fullName = getFullName();
}
also in for loop , you need to change
list.add(new Tenant(tnt.getFullName(), tnt.getAptNumber(),
tnt.getFirstPayment(), tnt.getmonthlyPayment()));
to -
list.add(new Tenant(tnt.getFirstName(),tnt.getLastName(), tnt.getAptNumber(),
tnt.getFirstPayment(), tnt.getmonthlyPayment()));

When using a for loop to add objects to an array, the last object that is added is used for all instances

Ive been trying to use a for loop to add instances of a driver to a driver array. Each driver has 3 basic variables that are gathered through the for loop. When the loop runs though, the details of the last driver are stored in all of the indexes of the array! I want to get it so that i can add each individual driver to the array.
public static void addDriver(Driver[] d) { //method using for loop to add drivers
for(int i = 0; i < d.length; i++ ) {
String name, DOB, occupation;
System.out.println("Please Enter Driver Name");
name = kb.nextLine();
System.out.println("Please Select Driver Occupation");
System.out.println("1: Chauffeur" + "\n2: Accountant");
int choice = kb.nextInt();
kb.nextLine();
if (choice == 1) {
occupation = "Chauffeur";
} else {
occupation = "Accountant";
}
System.out.println("Please Enter Driver D.O.B");
DOB = kb.nextLine();
d[i] = new Driver(name, occupation, DOB);
}
}
any and all help greatly appreciated!
edit...
here is the code from the main method, i get the size of the array from a separate method called driverNum.
public static void main(String[] args) {
int drivers = driverNum(); //Setting size of the array
Driver[] d = new Driver[drivers]; //creating new array using number of drivers to be insured
addDriver(d); //calling method to add drivers to array
for(int x = 0; x < d.length; x++)
{
System.out.println(d[x].toString());
}
}
here is the Driver class that i have been using...
public class Driver {
static String name, occupation, DOB;
public Driver()
{
name = "";
occupation = "";
DOB = "";
}
public Driver(String name, String occupation, String DOB)
{
this.name = name;
this.occupation = occupation;
this.DOB = DOB;
}
public void setName(String name)
{
this.name = name;
}
public String getName(Driver d)
{
return name;
}
public void setOccupation(String occupation)
{
this.occupation = occupation;
}
public String getOccupation()
{
return occupation;
}
public void setDOB(String DOB)
{
this.DOB = DOB;
}
public String getDOB()
{
return DOB;
}
public String toString()
{
String s;
s = "Name: " + name;
s = s + "\nOccupation: " + occupation;
s = s + "\nDOB: " + DOB;
return s;
}
}
Ive been scratching my head over this for a while now, because i thought it was correct. Thanks for the help so far!
In your Driver class, you defined your three global variables, name, occupation, and D.O.B as static. This means that whenever you change the value of that variable, it will change everywhere in the program, even if you create multiple instances of that class. Just take out the static declaration and that should solve your problem.

Java - Pass double as arguments without giving actual value

Got an error at : Movie m = new Movie(id, name, cost);
"cannot find symbol - var cost"
cost is set only when user insert input and cannot put actual value e.g.200.00
What should I put as argument?
Also, Session can only be created if user enters correct movie ID.
How do I match compare input(int) to an array?
Any help will be appreciated. Explanation is also important for me
Movie Class:
private void addMovie()
{
System.out.println("Setup a Movie");
int id = movies.setId();
String name = In.readString("Enter Movie Name: ");
double cost = In.readDouble("Enter Movie Cost:" );
Movie movie = new Movie(id, name, cost);
movies.add(movie);
menu();
}
Session Class:
private void addSession()
{
System.out.println("Add a Session");
int id = sessions.setId();
String name = In.readString("Enter Session Name: ");
int movieId = In.readInt("Enter Movie id:" );
**//match input with id array**
int theatreId = In.readInt("Enter Theatre id:" );
**//match input with theatre id array**
String sessionTime = In.readString("Enter Session Time - 0 for 9am, 1 for 12noon, 2 for 3pm or 3 for 6pm: ");
double GoldSeatsPrices = In.readDouble("Enter Prices fro Gold Class Seats:");
double ReguSeatsPrices = In.readDouble("Enter Prices for Regular Seats:");
Movie m = new Movie(id, name, cost);
Session session = new Session(id, name, m);
sessions.add(session);
menu();
}
Movie Class:
public class Movie extends Record
{
private double cost;
public Movie(int id, String name, double cost)
{
super(id, name);
this.cost = cost;
}
public double getCost()
{
return cost;
}
public String toString()
{
return "Movie: "+ super.toString() + " cost: $"+ cost;
}
}
Records Class: (super.):
import java.util.*;
/**
* class Records - complete
*/
public class Records
{
protected LinkedList<Record> records = new LinkedList<Record>();
protected int id = 0;
protected Record find(int id)
{
for(Record record: records)
{
if (record.matches(id))
return record;
}
return null;
}
protected void add(Record record)
{
records.add(record);
}
public int size()
{
return records.size();
}
public void show()
{
System.out.println(toString());
}
public String toString()
{
String str = "";
for(Record record : records)
str += record.toString() + "\n";
return str;
}
}
Record:
/**
* class Record - complete
*/
public class Record
{
protected int id;
protected String name;
public Record(int id, String name)
{
this.id = id;
this.name = name;
}
public String getName()
{
return name;
}
public int getId()
{
return id;
}
public boolean matches(int id)
{
return this.id == id;
}
public String toString()
{
return id + " " + name;
}
}
To the first question: There is no variable cost within addSession(). If you have not defined an attribute cost within Session then this is the problem.
To the second question: I am not quite sure that I understand your problem correctly. You have an int[] values and want to know, whether a given int x is within that array? If so, you can achieve this with this code snippet:
for (int value : values) {
if (value == x) {
// Put code, that should be executed when the value is found, here
}
}
Can you place the Super class Record also in your question?
Probably, you need to check the super constructor, which is differing from your sub class constructor.

How to extract object from set by part of fields in its class

Assume I have some class
public class CashCard {
private String lastName;
private int pinCode;
private int balance;
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public int getPinCode() {
return pinCode;
}
public void setPinCode(int pinCode) {
this.pinCode = pinCode;
}
public int getBalance() {
return balance;
}
public int takeMoney(int money) throws NotEnoughMoneyException {
if (money > balance)
throw new NotEnoughMoneyException();
balance -= money;
return money;
}
public int putMoney(int money) {
balance += money;
return money;
}
public CashCard(String lastName, int pinCode, int balance) {
this.lastName = lastName;
this.pinCode = pinCode;
this.balance = balance;
}
#Override
public boolean equals(Object o) {
if (o == null || o.getClass() != this.getClass())
return false;
if (o == this)
return true;
CashCard that = (CashCard) o;
return this.lastName.equals(that.lastName) && this.pinCode == that.pinCode;
}
#Override
public int hashCode() {
int result = 17;
int prime = 31;
result = result * prime + lastName.hashCode();
result = result * prime + pinCode;
return result;
}
}
the main point in this class is that it has 3 fields but for 2 objects of this class if they have same(equivalent) two fields they are equal no matter what third field is for each of them
Next, for example I have some set of this objects
CashCard card1 = new CashCard("Goldman", 1111, 9000);
CashCard card2 = new CashCard("Miranda", 1234, 100);
CashCard card3 = new CashCard("Grey", 6969, 1000000);
Set<CashCard> cashCards = new HashSet<CashCard>();
cashCards.add(card1);
cashCards.add(card2);
cashCards.add(card3);
The last thing - I have last name and pincode
String lastName = "Goldman";
int pincode = 1111;
I need to figure out if set contains element with such name and pincode AND if it is so, change that element in set in some way.
You can't extract the object which matches some constraint directly. You can only check for containment. To actually find that particular object you're after, you'll have to iterate over the set using an iterator and compare each object with the one you've constructed. That is, do something as follows:
for (CashCard cc : cashCards)
if (cc.equals(new CashCard("Goldman", 1111, 0L))
cc.balance -= toDebit;
If you don't share the reference in other places, you could also remove the CashCard and insert a new CashCard with the updated property:
CashCard newCard = new CashCard("Goldman", 1111, newBalance);
cashCards.remove(newCard);
cashCards.add(newCard);
I would strongly advice you to rethink your design though. Excluding one field from equals/hashcode is a real code smell. Consider making CashCard contain name+pin and use a Map<CashCard, Long> balanceMap for balances instead.

Categories

Resources