I desperately need help. I have two classes.
One is a PatientRecord with nested classes in it.
The other is a PatientGenerator which fills a database with PatientRecords by generating random data
for each field of the PatientRecord.
My problem is that I can't access the variables of some of the nested classes but I can access others. (At least it compiles for some and fails with an error for others.)
error: cannot find symbol
temp.fname = getRFirstName();
symbol: variable fname
location: variable temp of type PatientRecord.Visitor
Here is the failing calls
private ArrayList<PatientRecord.Visitor> generateVisitors(PatientRecord p) {
int payments = rnd.nextInt(10);
ArrayList<PatientRecord.Visitor> array = new ArrayList<PatientRecord.Visitor>();
for (int i = 0; i < payments; i++) {
PatientRecord.Visitor temp = p.new Visitor();
temp.fname = getRFirstName();
temp.lname = getRLastName();
temp.relation = relations[rnd.nextInt(relations.length)];
array.add(temp);
}
return array;
}
and here is part of the class with nested class Visitor in it.
public class PatientRecord implements Serializable{
public int pId;
public String FirstName;
public String MiddleName;
public String LastName;
public boolean gender;
public Location location;
public ArrayList visitors;
public ArrayList emergencyContacts;
public DateTime discharge;
public Admission admission;
public String primaryDoctor;
public ArrayList procedures;
public ArrayList prescriptions;
public ArrayList nurseNotes;
public ArrayList doctorNotes;
public InsurancePolicy insurancePolicy;
public ArrayList billing; // Arraylist of payments
public PatientRecord() {
init();
}
public PatientRecord(int id) {
pId = id;
init();
}
private void init() {
visitors = new ArrayList<Visitor>();
emergencyContacts = new ArrayList<Contact>();
location = new Location();
discharge = new DateTime();
admission = new Admission();
procedures = new ArrayList<Procedure>();
prescriptions = new ArrayList<Prescription>();
nurseNotes = new ArrayList<Note>();
doctorNotes = new ArrayList<Note>();
billing = new ArrayList<Payment>();
insurancePolicy = new InsurancePolicy();
}
public class Visitor {
public String fname;
public String lname;
public String relation;
public Visitor() {
}
}
I have no compilation errors (after having removed some of the code):
public class PatientRecord
{
public int pId;
public String FirstName;
public String MiddleName;
public String LastName;
public boolean gender;
public ArrayList visitors;
public ArrayList emergencyContacts;
public String primaryDoctor;
public ArrayList procedures;
public ArrayList prescriptions;
public ArrayList nurseNotes;
public ArrayList doctorNotes;
public ArrayList billing; // Arraylist of payments
public PatientRecord() {
init();
}
public PatientRecord(int id) {
pId = id;
init();
}
private void init() {
visitors = new ArrayList<Visitor>();
}
public class Visitor
{
public String fname;
public String lname;
public String relation;
}
public class PatientGenerator
{
public ArrayList<PatientRecord.Visitor> generateVisitors(PatientRecord p) {
//int payments = rnd.nextInt(10);
ArrayList<PatientRecord.Visitor> array = new ArrayList<PatientRecord.Visitor>();
for (int i = 0; i < 10; i++) {
PatientRecord.Visitor temp = p.new Visitor();
temp.fname = "first";
temp.lname = "last";
temp.relation = "brother";
array.add(temp);
}
return array;
}
}
public static void main(String[] args)
{
PatientRecord t = new PatientRecord();
PatientGenerator c = t.new PatientGenerator();
c.generateVisitors(t);
}
}
Does your code look similar to this?
Related
So I'm trying to access members inside my relation array, once it has been initialized. However it does not let me do so. What am I doing wrong?
public class FamilyRelations {
private Relationship [] relation;
public static void main(String[] args) {
FamilyRelations family = new FamilyRelations();
Scanner scanner = new Scanner(test);
family.run(scanner);
}
private void run(Scanner scanner) {
noOfRelations = 3;
relation= new Relationship [3];
System.out.println(relation[0].child); // Why does this raise nullpointerexception?
// Here I want to do relation[0].father = "John"; for example
}
public class Relationship {
public String child;
public String father;
public String mother;
public Relationship() {
this.child = "hej";
this.father = "father";
// this.mother = mother;
}
(I'm a beginner so this may sound obvious/lack information.) I have an ArrayList of attributes for different pets including attributes such as their given-name, common-name, the price of the animal, sex, date bought and date sold. this information is generated from a separate class that adds an array of information to an array of arrays of the already existing list of animals. Essentially, I want to send the array to another class (called Pets) so it can then be added to the array of arrays. I understand this may sound confusing but this is the only way I can word it, I can clarify anything if needed. Any help would be great as I'm really stuck and can't work out how to send it. This is the code that generates my values in the array (using text-boxes to input the information).
public void actionPerformed(ActionEvent e) {
ArrayList<String> NewanimalArr = new ArrayList<>();
String givenName = txtGivenname.getText();
String commonName = txtCommonName.getText();
String priceOf = txtPrice_1.getText();
String sexOf = txtSex.getText();
String colourOf = txtMaincolour.getText();
String dateOfA = txtArrivaldate.getText();
String dateSold = txtSellingdate.getText();
NewanimalArr.add(givenName);
NewanimalArr.add(commonName);
NewanimalArr.add(priceOf);
NewanimalArr.add(sexOf);
NewanimalArr.add(colourOf);
NewanimalArr.add(dateOfA);
NewanimalArr.add(dateSold);
System.out.println(NewanimalArr);
}
});
this will then print information generated that is entered for example:
[alex, Dog, 40.50, Male, Brown, 14/04/2015, 14/12/2016]
how do I then send this data to another class
Option one Constructor Injection:
public class Foo {
List<String> actionPerformed(ActionEvent e) {
List<String> newanimalArr = new ArrayList<>();
.....
return newanimalArr
}
...
public class Pets {
private final List<String> array;
public Pets(final List<String> array) {
this.array = array;
}
void bar() {
System.out.println(this.array);
}
}
....
public static void main(String[] args) {
Foo foo = new Foo();
Pets pets = new Pets(foo.actionPerformed( new ActionEvent() ) );
pets.bar();
}
Option two Getter-Setter Injection:
public class Foo {
private final List<String> newanimalArr;
public Foo() {
this.newanimalArr = new ArrayList<>();
}
public void actionPerformed(ActionEvent e) {
.....
}
public List<String> getNewanimalArr() {
return new ArrayList<String>(newanimalArr);
}
}
...
public class Pets {
private List<String> array;
public Pets() {
this.array = Collections.<String>emptyList();
}
public void setArray(final List<String> array) {
this.array = array;
}
public void bar() {
System.out.println(this.array);
}
}
....
public static void main(String[] args) {
Foo foo = new Foo();
foo.actionPerformed( new ActionEvent() );
Pets pets = new Pets();
bar.setArray( foo.getNewanimalArr() );
pets.bar();
}
See also Dependency Injection Patterns
Create a class definition of Pet, using instance variables for the fields. In Java it is custom to create a setXyz and a getXyz for each xyz field. You can also create a constructor in which you pass all the values and assign them to the fields, this minimizes the risk of fields not being filled in.
The initial ArrayList you are creating doesn't add that much use, it is easier to create the Pet instances directly:
List<Pet> newArrivals = new ArrayList<>();
// get data from view fields and if necessary transform them to other objects such as:
LocalDate arrivedOn = LocalDate.parse(txtArrivaldate.getText(), DateTimeFormatter.ofLocalizedDate(FormatStyle.FormatStyle);
// create and add a new Pet object to the list
newArrivals.add(new Pet(.....));
public class Pet {
public enum Gender {
FEMALE, MALE
}
private String givenName;
private String commonName;
private double price;
private Gender gender;
private String color;
private LocalDate arrivedOn;
private LocalDate soldOn;
public Pet() {
}
public Pet(String givenName, String commonName, double price, Gender gender, String color, LocalDate arrivedOn,
LocalDate soldOn) {
super();
this.givenName = givenName;
this.commonName = commonName;
this.price = price;
this.gender = gender;
this.color = color;
this.arrivedOn = arrivedOn;
this.soldOn = soldOn;
}
public String getGivenName() {
return givenName;
}
public void setGivenName(String givenName) {
this.givenName = givenName;
}
public String getCommonName() {
return commonName;
}
public void setCommonName(String commonName) {
this.commonName = commonName;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public Gender getGender() {
return gender;
}
public void setGender(Gender gender) {
this.gender = gender;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public LocalDate getArrivedOn() {
return arrivedOn;
}
public void setArrivedOn(LocalDate arrivedOn) {
this.arrivedOn = arrivedOn;
}
public LocalDate getSoldOn() {
return soldOn;
}
public void setSoldOn(LocalDate soldOn) {
this.soldOn = soldOn;
}
}
hope someone can help me. I have to two POJOS, one for the Invoice Header and another one for the details
public class Invoice{
private SimpleStringProperty docNum;
private SimpleStringProperty customer;
private ArrayList<InvoiceDetails> invoiceDetails;
public Invoice(String docNum, String customer) {
this.docNum = new SimpleStringProperty(docNum);
this.customer = new SimpleStringProperty(customer);
this.invoiceDetails= new ArrayList<>();
}
/* Getters and setters*/
}
the second one is...
public class InvoiceDetails{
private SimpleStringProperty taxRate;
private SimpleDoubleProperty taxAmount;
private SimpleDoubleProperty amount;
public InvoiceDetails(String taxRate, Double taxAmount, Double amount) {
this.taxRate= new SimpleStringProperty(taxRate);
this.taxAmount= new SimpleDoubleProperty(taxAmount);
this.amount= new SimpleDoubleProperty(amount);
}
/* Getters and setters*/
}
The question is how can I bind a field of the POJO Invoices, to the sum of the field amount of the POJO InvoiceDetails. Something like this:
public class Invoice{
private SimpleStringProperty docNum;
private SimpleStringProperty customer;
private ArrayList<InvoiceDetails> invoiceDetails;
private SimpleDoubleProperty totalAmount;
public Invoice(String docNum, String customer) {
this.docNum = new SimpleStringProperty(docNum);
this.customer = new SimpleStringProperty(customer);
this.invoiceDetails= new ArrayList<>();
this.totalAmount.bind(....)
}
/* Getters and setters*/
}
Which would be the better way to achive this. Maybe collecting the data in a stream and binding to the field totalAmount?
Thanks in advance for you time.
I think you can just extend a List (the example shows ArrayList extension) and change the field on list members changes.
public class DemoList {
public static void main(String[] args) throws Exception {
DetailList list = new DetailList();
Invoice i = new Invoice(list);
System.out.println(i.getTotalAmount());
list.add(new Details(42));
list.add(new Details(42));
System.out.println(i.getTotalAmount());
list.remove(0);
System.out.println(i.getTotalAmount());
}
}
class Invoice {
final DetailList details;
public Invoice(DetailList details) {
this.details = details;
}
public int getTotalAmount() {
return details.getTotalAmount();
}
}
class Details {
final int amount;
public Details(int amount) {
this.amount = amount;
}
}
class DetailList extends ArrayList<Details> {
int totalAmount=0;
public DetailList() {
}
#Override
public boolean add(Details t) {
boolean res = super.add(t);
recalculateTotal();
return res;
}
#Override
public void add(int index, Details element) {
super.add(index, element);
recalculateTotal();
}
#Override
public Details remove(int index) {
Details res = super.remove(index);
recalculateTotal();
return res;
}
#Override
public boolean remove(Object o) {
boolean res = super.remove(o);
recalculateTotal();
return res;
}
private void recalculateTotal() {
totalAmount=0;
this.stream().forEach(item -> {
totalAmount+=item.amount;
});
}
public int getTotalAmount() {
return totalAmount;
}
}
Thank you all for your time. I finally found out another solution that I think is more simple.
I bind the SimpleDoubleProperty totalAmount to a DoubleBinding, and this one is the result of a stream through the ArrayList<InvoiceDetails> invoiceDetails.
public class Invoice{
private SimpleStringProperty docNum;
private SimpleStringProperty customer;
private ArrayList<InvoiceDetails> invoiceDetails;
private SimpleDoubleProperty totalAmount;
public Invoice(String docNum, String customer) {
this.docNum = new SimpleStringProperty(docNum);
this.customer = new SimpleStringProperty(customer);
this.invoiceDetails= new ArrayList<>();
}
/* Getters and setters */
public SimpleDoubleProperty totalAmountProperty() {
if (this.totalAmount == null) {
this.totalAmount = new SimpleDoubleProperty();
}
DoubleBinding ta = new DoubleBinding() {
#Override
protected double computeValue() {
Double result = detalleIvaList.stream()
.mapToDouble(DetalleIva::getBaseImponible).reduce(0.0, Double::sum);
return new BigDecimal(result).setScale(2, RoundingMode.HALF_UP).doubleValue();
}
};
this.totalAmount.bind(ta);
return this.totalAmount;
}
public Double getTotalAmount() {
return this.totalAmountProperty().get();
}
public void setTotalAmount(Double totalAmount) {
this.totalAmountProperty().set(totalAmount);
}
Thanks again for your time.
Regards
it's been a while since I've done some java coding.
I need to build an application for a business which requires automation (part of a workshop), which is however irrelevant to my question...
I'm stuck on the line : customerList.add(customer); //(part of the addCustomer method in the WCIA class)
Also it's the first time I'm told to "Assign return value to new Variable" as part of an error, so not too sure what that means.
Code: Main
import java.util.ArrayList;
public class WCIA {
private final ArrayList customerList = null;
public static void main(String[] args) {
short s =002;
Customer arno = new Customer();
arno.setName("Arno");
arno.setId(s);
arno.setEmail("arnomeye#gmail.com");
arno.setAddress("Somewhere");
arno.setPhoneNum("0727855201");
System.out.printf("%s",arno.getEmail());
WCIA wcia = new WCIA();
wcia.addCustomer(arno);
wcia.displayCustomers();
}
public void addCustomer (Customer customer)
{
customerList.add(customer); // <---Problem over here
}
public void displayCustomers()
{
for(int x=0;x<customerList.size();x++)
{
Customer cus = (Customer) customerList.get(x);
cus.DisplayCustomer();
}
}
}
Code: Customer class:
public class Customer {
private short id;
private String name;
private String email;
private String phoneNum;
private String address;
public Customer()
{
System.out.println("Class initiated");
}
public void DisplayCustomer()
{
System.out.append("Name : "+ name+"\n");
System.out.append("ID : "+ id+"\n");
System.out.append("Email : "+ email+"\n");
System.out.append("Phone Number : "+ phoneNum+"\n");
System.out.append("address : "+ address+"\n");
}
public void setId(short id) {
this.id = id;
}
public void setName(String name) {
this.name = name;
}
public void setEmail(String email) {
this.email = email;
}
public void setPhoneNum(String phoneNum) {
this.phoneNum = phoneNum;
}
public void setAddress(String address) {
this.address = address;
}
public short getId() {
return id;
}
public String getName() {
return name;
}
public String getEmail() {
return email;
}
public String getPhoneNum() {
return phoneNum;
}
public String getAddress() {
return address;
}
}
You need to instantiate your ArrayList before you can assign elements to it. You're probably getting a NullPointerException, is my guess.
Change this line:
private final ArrayList customerList = null;
to
private final ArrayList customerList = new ArrayList();
Should solve at least this problem. I did not read the rest of your code so I'm not sure if other problems exist.
customerList is null and never initialized. Create an object of type ArrayList and assign it to that variable before you try to add to it.
You should declare the List with an explicit definition of the type of its elements (parametrized list):
private final List<Customer> customerList;
This way you can get rid of casting to Customer in:
Customer cus = customerList.get(x);
Finally, as good practice, initialize it in the constructor:
public WCIA()
{
customerList = new ArrayList<>();
}
So, I've got to write an invoice for a video store that has a Customer class which takes six attributes, the customer name (string), the street address (string), the city(String), the state(string), the zip code(string), and the telephone number. I had to use a parameterized constructor that receives the attributes as parameters as well as provide getters and setters. I believe I did this correctly.
Next I had to make a Video class that had four attributes, the video name (string), the year the video was released(integer), the video copy number(integer), and the daily rental rate(double). I had to do a parameterized constructor and getters and setters for this as well.
The problems start on my Invoice class which is to represent the rental of a video to a given customer, it is not finished, but is supposed to have four attributes, the customer renting the video, the video being rented, the date it was rented(as a inputted string), and the daily rental rate(double). It was also supposed to have three methods, the subtotal, the tax and the total. My problem is I've got the preset methods for the customers and the videos setup, I just have no clue how to effectively use them in an if statement. I don't know what I would put in my fourth test class to allow this to work. I am all but lost at this point, any push in the right direction would be greatly appreciated. here are my classes.
Customer:
public class Customer {
private String customerName;
private String streetAddress;
private String custCity;
private String custState;
private String custZip;
private String custPhone;
public Customer(String customerName, String streetAddress, String custCity, String custState, String custZip,
String custPhone) {
super();
this.customerName = customerName;
this.streetAddress = streetAddress;
this.custCity = custCity;
this.custState = custState;
this.custZip = custZip;
this.custPhone = custPhone;
}
public String getCustomerName() {
return customerName;
}
public void setCustomerName(String customerName) {
this.customerName = customerName;
}
public String getStreetAddress() {
return streetAddress;
}
public void setStreetAddress(String streetAddress) {
this.streetAddress = streetAddress;
}
public String getCustCity() {
return custCity;
}
public void setCustCity(String custCity) {
this.custCity = custCity;
}
public String getCustState() {
return custState;
}
public void setCustState(String custState) {
this.custState = custState;
}
public String getCustZip() {
return custZip;
}
public void setCustZip(String custZip) {
this.custZip = custZip;
}
public String getCustPhone() {
return custPhone;
}
public void setCustPhone(String custPhone) {
this.custPhone = custPhone;
}
}
Video:
public class Video {
private String videoName;
private int videoYear;
private int copyNum;
private double rentalRate;
public Video(String videoName, int videoYear, int copyNum, double rentalRate) {
super();
this.videoName = videoName;
this.videoYear = videoYear;
this.copyNum = copyNum;
this.rentalRate = rentalRate;
}
public String getVideoName() {
return videoName;
}
public void setVideoName(String videoName) {
this.videoName = videoName;
}
public int getVideoYear() {
return videoYear;
}
public void setVideoYear(int videoYear) {
this.videoYear = videoYear;
}
public int getCopyNum() {
return copyNum;
}
public void setCopyNum(int copyNum) {
this.copyNum = copyNum;
}
public double getRentalRate() {
return rentalRate;
}
public void setRentalRate(double rentalRate) {
this.rentalRate = rentalRate;
}
Invoice (incomplete) :
import java.util.Scanner;
public class Invoice {
public static void main(String[] args){
Scanner in = new Scanner(System.in);
Customer Brandon = new Customer("Brandon James" , "112 Oak Street"
, "CityVille" , "Alabama" , "18229",
"912-2248");
Customer Judy = new Customer("Judy Vermooth" , "8008 Ribbit Ln.",
"Metropolis" , "Pennsylvania" , "24057", "241-8009");
Video Easter = new Video("Easter 2", 2002, 4, 2.49);
Video DareDevil3 = new Video ("Dare Devil 3", 2012, 2, 3.62);
if( Prog4.newRental = "Brandon"){
Customer Brandon = newCust
}
}
}
Prog4(incomplete):
import java.util.*;
public class Prog4 {
private String newRental;
private String vidName;
private String rentalDate;
private String daysRented;
public static void main(String[] args){
Scanner in = new Scanner(System.in);
System.out.println("Enter Customer Name: ");
String newRental = in.nextLine();
System.out.println("Enter Video Name: ");
String vidName = in.nextLine();
System.out.println("Enter Rental date in mm/dd/yyyy format: ");
String rentalDate = in.nextLine();
System.out.println("Enter Number of Days Rented");
int daysRented = in.nextInt();
}
public String getNewRental() {
return newRental;
}
public void setNewRental(String newRental) {
this.newRental = newRental;
}
public String getVidName() {
return vidName;
}
public void setVidName(String vidName) {
this.vidName = vidName;
}
public String getRentalDate() {
return rentalDate;
}
public void setRentalDate(String rentalDate) {
this.rentalDate = rentalDate;
}
public String getDaysRented() {
return daysRented;
}
public void setDaysRented(String daysRented) {
this.daysRented = daysRented;
}
}