Send array data from one class to another JAVA - java

(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;
}
}

Related

How to create a better object

Related to my previous thread, i want to print an output like this:
bookId = "1234" (String)
bookName = "Machine Learning" (String)
price = $20 (int)
ratings = (array of object)
rater = a, score = 5
rater = b, score = 3
But this time, i tried to use an OOP manner.
So first, i made a POJO class called ProductView, the class will be look like this:
public class ProductView {
// field
private String bookId;
private String bookName;
private int price;
private List<Ratings> ratings;
// a constructor i tried to make
public ProductView(String bookId, String bookName, int price, List<Ratings> ratings) {
this.bookId = bookId;
this.bookName = bookName;
this.price = price;
this.ratings = ratings;
}
public String getBookId() {
return bookId;
}
public void setBookId(String bookId) {
this.itemId = itemId;
}
public String getBookName() {
return bookName;
}
public void setBookName(String bookName) {
this.bookName = bookName;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
public Ratings getRatings() {
return ratings;
}
public void setRatings(Ratings ratings) {
this.ratings = ratings;
}
}
After that, i made a class called Ratings with the following field:
public class Ratings {
private String rater;
private int score;
public Ratings(String rater, int score) {
this.rater = rater;
this.score = score;
}
}
And finally, i made a Main Class called Main:
public class Main {
public static void main(String[] args) {
}
}
In the Main Class, i want to create an instance of the ProductView class and give it some value.
But i don't know how to do it with a list object param in my constructor.
Anyone can give me some insight?
first:
List is an interface, you should pass an implementation of list such as ArrayList or similar
second:
you have a compilation error in ProductView -> SetBookId, in this.itemId you don't have itemId as member or constructor parameter
furthermore, in get/set rating you need to pass and return list of Ratings.
nameing:
Ratings is actually just a Rating, you can make a new class of List or just use the Rating as is but change the name
now for your Question:
you can initialize first the list with objects and then send it to the constructor
such as:
List<Ratings> ratings = new ArrayList<>();
ratings.add(new Ratings("rater",5));
ratings.add(new Ratings("rater2",6));
ProductView productView = new ProductView("bookId","bookName",1,ratings);
Or, just initialize the ArrayList in the Constructor, the first way is preferable:
ProductView productView1 = new ProductView("bookId","bookName",1,
new ArrayList<Ratings>(Arrays.asList(new Ratings("rater",5), new Ratings("rater2",6))
));
hopefully, this answers your question
same as DodgyCodeException mentioned in the comments.

Creating an object and calling it

this is my current code to store rooms(it compiles fine) but in the UML there is a variable called addEquipment and there is also another class called Equipment to be defined. I'm having trouble wrapping my head around what I'm supposed to do with this. Am I supposed to create and call an object called Equipment? what goes in addEquipment?
public class Room {
//begin variable listing
private String name;
private int id;
private int capacity;
private String equipmentList;
//begins get methods for variables
public String getName(){
return name;
}
public int getID(){
return id;
}
public int getCapacity(){
return capacity;
}
public String getEquipmentList(){
return equipmentList;
}
// Set the variables
public void setName(String aName){
name=aName;
}
public void setID(int anID){
id=anID;
}
public void setCapacity(int aCapacity){
capacity=aCapacity;
}
public void setEquipmentList(String anEquipmentList){
equipmentList=anEquipmentList;
}
public String addEquipment(String newEquipment, String currentEquipment){
}
//Create room object
public Room(int capacity, String equipmentList) {
setCapacity(capacity);
setEquipmentList(equipmentList);
}
//Convert variables to string version of room
public String toString(){
return "Room "+name+", capacity: "+capacity+", equipment: "+getEquipmentList();
}
}
You can create a new class Equipment and modify your attribute equipmentList to be a List:
public class Equipment {
private String name;
public Equipment(String name) {
this.name = name;
}
}
public class Room {
//begin variable listing
private String name;
private int id;
private int capacity;
private List<Equipment> equipmentList = new ArrayList<Equipment>();
//begins get methods for variables
public String getName(){
return name;
}
public int getID(){
return id;
}
public int getCapacity(){
return capacity;
}
public List<Equipment> getEquipmentList(){
return equipmentList;
}
// Set the variables
public void setName(String aName){
name=aName;
}
public void setID(int anID){
id=anID;
}
public void setCapacity(int aCapacity){
capacity=aCapacity;
}
public void setEquipmentList(List<Equipment> anEquipmentList){
equipmentList=anEquipmentList;
}
public String addEquipment(String newEquipment, String currentEquipment){
Equipment oneEquipment = new Equipment(newEquipment);
equipmentList.add(oneEquipment);
}
//Create room object
public Room() {
setCapacity(capacity);
setEquipmentList(equipmentList);
}
//Convert variables to string version of room
public String toString(){
String capacity=String.valueOf(getCapacity());
String room = "Room "+name+", capacity: "+capacity+", equipment: "+getEquipmentList();
return room;
}
}
In the method addEquipment, you can create a new Equipment and add it to equipmentList, like code above.
An Equipment class could be anything. Lets assume the "Equipment"-class has a String called "name" as it's attribute
public class Equipment {
String name;
public Equipment( String name) {
this.name = name;
}
public String getName() {
return this.name
}
}
When you extend your Room class by the requested "addEquipment" method, you can do something like this.
public class Room {
... // Your code
private int equipmentIndex = 0;
private Equipment[] equipment = new Equipment[10]; // hold 10 Equipment objects
public void addEquipment( Equipment eq ) {
if ( equipmentIndex < 10 ) {
equipment[ equipmentIndex ] = eq;
equipmentIndex++;
System.out.println("Added new equipment: " + eq.getName());
} else {
System.out.println("The equipment " + eq.getName() + " was not added (array is full)");
}
}
}
Now when you call
room.addEquipment( new Equipment("Chair") );
on your previously initialized object of the Room-class, you will get
"Added new equipment: Chair"
Hope this helps a bit.
PS: The code is untestet (maybe there hides a syntax error somewhere)

Accessing getter variables

I have a class called Manufacturer and within it i have a an array of cars. In my main class, i declared an array of Manufacturer object. Car have attributes of model, price etc. How to i accessed the getter methods that i have declared in the Car class? Assume that my arrays are populated.
public class Main
{
public static void main(String[] args)
{
Manufacturer[] objManufacturer = new Manufacturer[10];
System.out.println(objManufacturer[0].getManufacturer());
// how do a print out the year of the first car in the first manufacturer?
}
}
Car Class
public class Car
{
private int year; // year of the car
private String model; // model of the car
private double price; // price of the car
private int kmTravelled; // the KM travelled by the car
private String extras; // extra information about the car
public Car()
{
}
// Parameterized constructor
public Car(int year, String model, double price,int kmTravelled, String extras )
{
this.year = year;
this.model = model;
this.price = price;
this.kmTravelled = kmTravelled;
this.extras = extras;
}
// getter method for Year
public int getYear()
{
return year;
}
}
class Manufacturer
public class Manufacturer
{
private String manufacturerName; // manufacturer of the car
private Car[] cars; // an array to store the cars
private int numOfCars;
//default constructor initialize car array size to 10
//and the current numOfCar to 0
public Manufacturer()
{
numOfCars = 0;
cars = new Car[10];
}
// getter methods for manufacturer
public String getManufacturerName()
{
return manufacturerName;
}
public void setManufacturer(String aManufacturer)
{
manufacturerName = aManufacturer;
}
}
First of all, you didn't define the getters and setters in your Car class, so do it:
public class Car
{
private int year; // year of the car
private String model; // model of the car
private double price; // price of the car
private int kmTravelled; // the KM travelled by the car
private String extras; // extra information about the car
public Car()
{
}
// Parameterized constructor
public Car(int year, String model, double price,int kmTravelled, String extras )
{
this.year = year;
this.model = model;
this.price = price;
this.kmTravelled = kmTravelled;
this.extras = extras;
}
// getter method for Year
public int getYear()
{
return year;
}
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public int getKmTravelled() {
return kmTravelled;
}
public void setKmTravelled(int kmTravelled) {
this.kmTravelled = kmTravelled;
}
public String getExtras() {
return extras;
}
public void setExtras(String extras) {
this.extras = extras;
}
public void setYear(int year) {
this.year = year;
}
}
Then you will have to create addCars and getNumOfCars in your Manufacturer:
public class Manufacturer
{
private String manufacturerName; // manufacturer of the car
private Car[] cars; // an array to store the cars
private int numOfCars;
//default constructor initialize car array size to 10
//and the current numOfCar to 0
public Manufacturer()
{
numOfCars = 0;
cars = new Car[10];
}
// getter methods for manufacturer
public String getManufacturerName()
{
return manufacturerName;
}
public void setManufacturer(String aManufacturer)
{
manufacturerName = aManufacturer;
}
public Manufacturer getManufacturer() {
return this;
}
public Car[] getCars() {
return cars;
}
public void addCar(Car car){
cars[numOfCars] = car;
numOfCars++;
}
public int getNumOfCars() {
return numOfCars;
}
}
Then you can acess from your main class:
public class Main {
public static void main(String[] args) throws ParseException, IOException, InterruptedException {
Manufacturer[] objManufacturer = new Manufacturer[10];
Manufacturer obj1 = new Manufacturer();
objManufacturer[0] = obj1;
System.out.println(objManufacturer[0].getManufacturer());
Car car1 = new Car(2014, "Gol", 20000, 0, null);
obj1.addCar(car1);
int numOfCars = obj1.getNumOfCars();
Car[] cars = obj1.getCars();
for (int i = 0; i < numOfCars; i++) {
Car car = cars[i];
System.out.println(car.getModel());
}
}
}
That is it!
objManufacturer[0].getCars()[0].getYear()
After you create a getter method for your array within the manufacterer class:
public getCars() { return cars; }
Firstly you don't have valid setters and getters.
public class Manufacturer{
private String manufacturerName; // manufacturer of the car
private Car[] cars; // an array to store the cars
private int numOfCars;
//default constructor initialize car array size to 10
//and the current numOfCar to 0
public Manufacturer(){
numOfCars = 0;
cars = new Car[10];
}
// getter methods for manufacturer
public String getManufacturerName(){
return manufacturerName;
}
public void setManufacturerName(String aManufacturer){
manufacturerName = aManufacturer;
}
public Car[] getCars(){
return cars;
}
public void setCars(Car[] cars){
this.cars = cars;
}
}
Main method:
public static void main(String[] args){
Manufacturer[] objManufacturer = new Manufacturer[10];
//Assuming that you have populated data properly
System.out.println(objManufacturer[0].getCars()[0].getYear());
//Gives year of first car of first manufacturer
}

Assign return value to new Variable (Java)

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<>();
}

How to use more than one method?

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;
}
}

Categories

Resources