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
}
Related
So i have create my Car class and now i need to sout the model Ferrari
here is my code (sout version)
for (int b = 0; b < carList.size(); b++) {
if (carList.get(b).getMark().equalsIgnoreCase("ferrari")) {
System.out.println("This is Ferrari : " + carList.get(b));
}
}
output for this code is :
This is Ferrari : Car{color='Green', price=300000, power=750, mark='Ferrari', model='SP-90', age='2020'}
This is Ferrari : Car{color='black', price=1305000, power=565, mark='Ferrari', model='Roma', age='2018'}
Since my list have 2 ferarri
Now i am curios how to use retrun(since i am new in this field) , to return the same output i have used with the (sout veriosn) above .
Try the below function to get all the Ferrari Car object list:
List<Car> getFerrariCarList(ArrayList<Car> carList){
List<Car> newCarList = new ArrayList<>();
for (int b = 0; b < carList.size(); b++) {
if (carList.get(b).getMark().equalsIgnoreCase("ferrari")) {
newCarList.add(carList.get(b));
// System.out.println("This is Ferrari : " + carList.get(b));
}
}
return newCarList;
}
Update 1:
Main2.java
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Main2 {
private static Object Car;
public static void main(String[] args) {
Car car1 = new Car("PodiumBlue", 18500, 165, "Fiat", "Abarth", 2019);
Car car2 = new Car("Blue", 9500, 105, "Renualt", "Laguna", 2001);
Car car3 = new Car("Green", 300000, 750, "Ferrari", "SP-90", 2020);
Car car4 = new Car("Black", 80500, 650, "BMW", "M5-Competition", 2021);
Car car5 = new Car("black", 1305000, 565, "Ferrari", "Roma", 2018);
List<Car> carList = Arrays.asList(car1, car2, car3, car4, car5);
List<Car> ferrariCars = getFerrariCarList(carList);
System.out.println(ferrariCars);
}
static List<Car> getFerrariCarList(List<Car> carList) {
List<Car> newCarList = new ArrayList<>();
for (int b = 0; b < carList.size(); b++) {
if (carList.get(b).getMark().equalsIgnoreCase("ferrari")) {
newCarList.add(carList.get(b));
}
}
return newCarList;
}
}
Car.java
public class Car {
private String color;
private int price;
private int power;
private String mark;
private String model;
private Integer age;
public Car(String color, int price, int power, String mark, String model, Integer age) {
this.color = color;
this.price = price;
this.power = power;
this.mark = mark;
this.model = model;
this.age = age;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
public int getPower() {
return power;
}
public void setPower(int power) {
this.power = power;
}
public String getMark() {
return mark;
}
public void setMark(String mark) {
this.mark = mark;
}
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
}
Developing this simple code:
public class Car {
String owner;
int year;
public Car (String owner, int year) {
this.owner = owner;
this.year = year;
}
public String getOwner() {
return owner;
}
public void setOwner(String owner) {
this.owner = owner;
}
public int getYear() {
return year;
}
public void setYear(int year) {
this.year = year;
}
On the other class, you want to create an object, assigning one value to the owner of the car, and a year to the car, and after this you want to modify the value of the owner of the car and modify the year of the car:
public OtherClass {
Car car = new Car("John", 2010);
car.setOwner("Mark"); // It causes error
car.setYear(2014); // It causes error
}
However, after you create an object and you put values on this object, how can you change the values of this object?
If you write: car.owner = "Mark" and car.year = 2014, the IDE doesn´t recognize it.
It was hard to explain in comments. so I am posting solution here.
It was compilation error. You can create OtherClass.java and paste this code run main method it will work.
class Car {
private String owner;
private int year;
public Car(String owner, int year) {
this.owner = owner;
this.year = year;
}
public void setOwner(String value) {
this.owner = value;
}
public String getOwner() {
return this.owner;
}
public void setYear(int value) {
this.year = value;
}
public int getYear() {
return this.year;
}
}
public class OtherClass {
public static void main(String[] args) {
Car car = new Car("John", 2010);
car.setOwner("Mark");
car.setYear(2014);
}
}
(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;
}
}
I have a tableview in javafx which i want to populate with objects type Course. The idea is that in my Course class, I hava a composite primary key which is a diifferent class CourseId. I want to add in one column of the tableview the courseno which is present in CourseId class, but i dont know how to get it.
My course class:
package com.licenta.ascourses.ui.model;
import java.io.Serializable;
public class Course implements Serializable {
private CourseId idCourse = new CourseId();
private int year;
private int semester;
private String discipline;
private String professor;
public Course() {
}
public Course(CourseId idCourse, int year, int semester) {
super();
this.idCourse = idCourse;
this.year = year;
this.semester = semester;
}
public Course(CourseId idCourse, int year, int semester, String discipline, String professor) {
this.idCourse=idCourse;
this.year = year;
this.semester = semester;
this.discipline = discipline;
this.professor = professor;
}
public CourseId getIdCourse() {
return idCourse;
}
public void setIdCourse(CourseId idCourse) {
this.idCourse = idCourse;
}
public int getYear() {
return year;
}
public void setYear(int year) {
this.year = year;
}
public int getSemester() {
return semester;
}
public void setSemester(int semester) {
this.semester = semester;
}
public String getDiscipline() {
return discipline;
}
public void setDiscipline(String discipline) {
this.discipline = discipline;
}
public String getProfessor() {
return professor;
}
public void setProfessor(String professor) {
this.professor = professor;
}
}
My courseId class:
package com.licenta.ascourses.ui.model;
import java.io.Serializable;
public class CourseId implements Serializable {
private int idDiscipline;
private int idProfessor;
private int courseNo;
public CourseId() {
}
public CourseId(int idDiscipline, int idProfessor, int courseNo) {
super();
this.idDiscipline = idDiscipline;
this.idProfessor = idProfessor;
this.courseNo = courseNo;
}
public int getIdDiscipline() {
return idDiscipline;
}
public void setIdDiscipline(int idDiscipline) {
this.idDiscipline = idDiscipline;
}
public int getIdProfessor() {
return idProfessor;
}
public void setIdProfessor(int idProfessor) {
this.idProfessor = idProfessor;
}
public int getCourseNo() {
return courseNo;
}
public void setCourseNo(int courseNo) {
this.courseNo = courseNo;
}
public boolean equals(Object o) {
return true;
}
public int hashCode() {
return 1;
}
}
columnNumarCurs.setCellValueFactory(new PropertyValueFactory<Course, Integer>(""));
columnAn.setCellValueFactory(new PropertyValueFactory<Course, Integer>("year"));
columnSemestru.setCellValueFactory(new PropertyValueFactory<Course, Integer>("semester"));
columnDisciplina.setCellValueFactory(new PropertyValueFactory<Course, String>("discipline"));
columnProfesor.setCellValueFactory(new PropertyValueFactory<Course, String>("professor"));
The setCellValueFactory method requires a Callback<CellDataFeatures, ObservableValue>: i.e. a function that maps a CellDataFeatures object to an ObservableValue containing the value to be displayed. Since the value you have is an int, and assuming columnNumarCurs is a TableColumn<Course, Number>, the appropriate ObservableValue type is an IntegerProperty. So you can do:
columnNumarCurs.setCellValueFactory(
cellData -> new SimpleIntegerProperty(cellData.getValue().getIdCourse().getCourseNo()));
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)