Java Array storing objects with multiple fields - java

I have public class Vehicle with two subclasses Car and Truck that each extend Vehicle. The constructor for each class is the same with 3 fields, color, brand and gas mileage.
I've declared an array
Vehicle [] vehArray = new Vehicle[6];
that will store 6 different vehicles. I know a call
Car car1 = new Car("Red", "Ford", 15);
will instantiate car1 with an object of type Car.
How would I store car1 in vehArray[0]?

Try doing something like this:
vehArray[0] = car1;

Shortest way is:
vehArray [0] = new Car("Red", "Ford", 15);

Or even
Vehicle[] vehArray = new Vehicle[]{new Car("Red", "Ford", 15), new Truck("Silver", "Mercedes", 2)};

As below;
1) Test.java;
public class Test {
public static void main(String[] args) {
//Array Initialization with null Vehicle placeholders
Vehicle[] vehicleArray = new Vehicle[6];
//Car class object instances are assiged
for( int i = 0; i < vehicleArray.length; i++ )
vehicleArray[i] = new Car("Red", "Ford", 15+i);
for( int i = 0; i < vehicleArray.length; i++ )
System.out.println
(
i +
" : " + vehicleArray[i].getColor() +
" : " + vehicleArray[i].getBrand() +
" : " + vehicleArray[i].getGasMilage()
);
}
}
2) Vehicle.java
public class Vehicle {
private String color;
private String brand;
private int gasMilage;
public Vehicle() {}
//Constructor with fields
public Vehicle(String color, String brand, int gasMilage) {
this.color = color;
this.brand = brand;
this.gasMilage = gasMilage;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public String getBrand() {
return brand;
}
public void setBrand(String brand) {
this.brand = brand;
}
public int getGasMilage() {
return gasMilage;
}
public void setGasMilage(int gasMilage) {
this.gasMilage = gasMilage;
}
}
3) Car.java
public class Car extends Vehicle {
//no-arg constructor
public Car() {
super();
}
//field constructor
public Car(String color, String brand, int gasMilage) {
super(color, brand, gasMilage);
}
}
4) Truck.java
public class Truck extends Vehicle {
//no-arg constructor
public Truck() {
super();
}
//field constructor
public Truck(String color, String brand, int gasMilage) {
super(color, brand, gasMilage);
}
}

I suggest declaring all objects of subclasses first then it can be stored in vehicle like so :
Vehicle[] vehicleArray = {ob1,ob2,ob3,ob4,andSo_On};

Do you mean calling parent class constructor so you can use the fields in parent class?
Here's my take :)
Vehicle.java
public class Vehicle {
String color, brand;
int mileage;
Vehicle(String c, String d, int e){
color = c;
brand = d;
mileage = e;
}
}
Car.java
public class Car extends Vehicle{
Car(String c, String d, int e){
super(c, d, e);
}
}
Test.java
public class Test {
public static void main(String[] args) {
Vehicle [] vehArray = new Vehicle[6];
Car car1 = new Car("Red", "Ford", 15);
Car car2 = new Car("Blue", "Audi", 17);
vehArray[0] = car1;
vehArray[1] = car2;
System.out.println("Color: " + car1.color + "\nBrand: " + car1.brand + "\nMileage: " + car1.mileage + "\n");
System.out.println("Color: " + car2.color + "\nBrand: " + car2.brand + "\nMileage: " + car2.mileage);
for(int i=0; i<2; i++) {
if(vehArray[i].color == "Blue")
{
System.out.println("\nCar is " + vehArray[i].brand);
}
}
}
}
I even did testing at the end just to make sure. You're welcome :D

Related

How to get Garage if full if there are more cars inside then parkingspaces availible

I have this Garage Class
import java.util.ArrayList;
import java.util.List;
public class Garage {
private int m3;
private String name;
private int parkingSpace;
List<Car> cars = new ArrayList<>();
List<Person> persons = new ArrayList<>();
public Garage(int m3, String name, int parkingSpace) {
this.m3 = m3;
this.name = name;
this.parkingSpace = parkingSpace;
}
public int getM3() {
return m3;
}
public void setM3(int m3) {
this.m3 = m3;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getParkingSpace() {
return parkingSpace;
}
public void setParkingSpace(int parkingSpace) {
this.parkingSpace = parkingSpace;
}
#Override
public String toString() {
return "Garage{" +
"m3=" + m3 +
", name='" + name + '\'' +
", parkingSpace=" + parkingSpace +
'}';
}
public void addCar1(Car newCar) {
if (cars.size() != parkingSpace)
cars.add(newCar);
}
public int getHowManyCarsFit() {
return parkingSpace - cars.size();
}
public int getHowManyCarsAreIn() {
return cars.size();
}
public void addCar(Car newCar) {
cars.add(newCar);
}
}
Here example of one of my garages (one that have the most cars)
Garage garage4 = new Garage(450, "garage4", 4);
garage4.addCar(car1);
garage4.addCar(car2);
garage4.addCar(car3);
garage4.addCar(car4);
garage4.addCar(car5);
So it should sout that "This garage is full !" when i add "car5" and ofcourse if there are 4 cars already
I try to do the folowing :
I took already how many cars i have in and witch is the garage with most cars.
Now i have to say if my garage have tha amount of casr af parking spcae or more cars the the parkingspaces "Garage is full! Please park outside!"
This is my code and what i have tryed in else if statmet
public static Garage getMostCars(List<Garage> garageList) {
Garage mostCars = null;
int cars = 0;
for (Garage garage : garageList) {
if (garage.getHowManyCarsAreIn() > cars) {
mostCars = garage;
cars = garage.getHowManyCarsAreIn();
} else if (garage.getHowManyCarsAreIn() >= garage.getHowManyCarsFit()) {
System.out.println("----------------------------");
System.out.println("Garage is full ! \n" + "You cannot add more cars , please go outside the garage");
}
}
System.out.println("------------------------------------");
System.out.println("There are currently: " + cars + " cars inside");
return mostCars;
}

Sorting and Binary Search (Java)

I was asked to sort a car array by model type and then use Arrays.binarySearch to search for a Car with that Model field. The problem is when the search is conducted it doesn't find anything (even though the model is in there).
Below is my code and output:
import java.util.Arrays;
import java.util.Comparator;
import java.util.Scanner;
public class CarApplication
{
public static void main (String[] args)
{
Scanner keyboard = new Scanner(System.in);
Car car1 = new Car("Toyota", "Corolla" , 1996);
Car car2 = new Car("Nissan", "Murano" , 2004);
Car car3 = new Car("Mazda" , "Miata", 1999);
Car car4 = new Car("Ford", "Mustang" , 2013);
Car car5 = new Car("Chevy", "Volt" , 2020);
Car car6 = new Car("Tesla", "Model X" , 2016);
Car [] myCars = {car1, car2, car3, car4, car5, car6};
Arrays.sort(myCars, new CompareByModel());
System.out.println("Sorting by Model only (Comparator)");
for (Car car:myCars)
System.out.println(car);
System.out.println("Enter the name of the car model you wish to purchase: ");
String model = keyboard.nextLine();
//binary search
Car key = new Car("", model, 0); // set the name field so we can look for a match in array
int location = Arrays.binarySearch(myCars, 0, myCars.length, key, new CompareByModel());
//print message
if (location < 0)
System.out.println("Sorry, please check back next week.");
else
{
System.out.println("We have a " + model + " in location" + myCars[location]);
}
}
}
//Comparator
class CompareByModel implements Comparator<Car>
{
public int compare(Car c1, Car c2) {
int makeResult = c1.getCarMake().compareTo(c2.getCarMake());
int modelResult = c1.getCarModel().compareTo(c2.getCarModel());
return (modelResult == 0) ? makeResult: modelResult;
}
}
Output:
Enter the name of the car model you wish to purchase:
Volt
Sorry, please check back next week.
When you sort, you sort by the make and model, which is cool. But when you try and search, you set the make to "", so the result of comparing the entities won't work correctly.
You could modify the sort Comparator so as to ignore makes with "" when comparing them (so only using models) or supply the make as part of your search or create a seperate "search" Comparator, for example
public class Main {
public static void main(String[] args) {
new Main();
}
public Main() {
Scanner keyboard = new Scanner(System.in);
Car car1 = new Car("Toyota", "Corolla", 1996);
Car car2 = new Car("Nissan", "Murano", 2004);
Car car3 = new Car("Mazda", "Miata", 1999);
Car car4 = new Car("Ford", "Mustang", 2013);
Car car5 = new Car("Chevy", "Volt", 2020);
Car car6 = new Car("Tesla", "Model X", 2016);
Car[] myCars = {car1, car2, car3, car4, car5, car6};
Arrays.sort(myCars, new SortComparator());
System.out.println(Arrays.toString(myCars));
String model = "Murano";
int result = Arrays.binarySearch(myCars, 0, myCars.length, new Car("", model, 0), new ModelComparator());
System.out.println(result);
int location = Arrays.binarySearch(myCars, 0, myCars.length, new Car("", model, 0), new SortComparator());
System.out.println(location);
}
public class Car {
private String make;
private String model;
private int year;
public Car(String make, String model, int year) {
this.make = make;
this.model = model;
this.year = year;
}
public String getMake() {
return make;
}
public String getModel() {
return model;
}
public int getYear() {
return year;
}
#Override
public String toString() {
return getMake() + " " + getModel() + " # " + getYear();
}
}
public static class SortComparator implements Comparator<Car> {
public int compare(Car c1, Car c2) {
int makeResult = c1.getMake().compareTo(c2.getMake());
int modelResult = c1.getModel().compareTo(c2.getModel());
return (modelResult == 0) ? makeResult : modelResult;
}
}
public static class ModelComparator implements Comparator<Car> {
public int compare(Car c1, Car c2) {
return c1.getModel().compareTo(c2.getModel());
}
}
}

Using parent class toString in object Array to print parent class variables for child class JAVA

I am trying to write a code that takes vehicle names and such and stores them in an array of objects. I have Vehicle as the parent class with a toString that prints the name, brand and gallons of tank, the two subclasses of parent are bus and car. Car and Bus ask how many doors,wheels or passengers. When printing the array out after randomizing the order i only get the to Strings from the parent class to print out when the index of the array is of the parent class. What i want to print out is:
Vehicle 0:
name: car brand: something : tanksize: 15
Doors: 4 : Wheels 4
My code is below:
import java.util.*;
public class Q1 {
public static void main(String args[]){
Scanner kb = new Scanner(System.in);
Vehicle[] list = new Vehicle[3];
for(int i =0;i < list.length;i++){
int random = (int)(Math.random()*3);
if(random == 0){
System.out.println("What is the Name, brand and how big is the gas tank of the vehicle?");
String name = kb.next();
String brand = kb.next();
int gasTank = kb.nextInt();
Vehicle a = new Vehicle(name,brand,gasTank);
list[i] = a;
}
else if(random == 1){
System.out.println("How many doors and wheels does the car have");
int doors = kb.nextInt();
int wheels = kb.nextInt();
System.out.println("What is the Name, brand and how big is the gas tank of the car?");
String name = kb.next();
String brand = kb.next();
int gasTank = kb.nextInt();
Car a = new Car(doors,wheels,name,brand,gasTank);
list[i] = a;
}
else{
System.out.println("How many doors and wheels does the bus have?");
int doors = kb.nextInt();
int wheels = kb.nextInt();
System.out.println("What is the Name, brand and how big is the gas tank of the bus?");
String name = kb.next();
String brand = kb.next();
int gasTank = kb.nextInt();
Bus a = new Bus(doors,wheels,name,brand,gasTank);
list[i] = a;
}
}
printArray2(list);
}
public static void printArray(Vehicle[] list){
for(int i = 0; i< list.length; i++){
System.out.println("Vehicle "+ i);
System.out.println(list[i]);
System.out.println("___________");
}
}
public static void printArray2(Vehicle[] list){
for(int i = 0; i< list.length;i++){
System.out.println("Vehicle "+ i);
System.out.println(list[i].toString());
System.out.println("___________");
}
}
}
class Vehicle {
String name;
String brand;
int gasTank;
public Vehicle(){
this(" ", " ", 15);
}
public Vehicle(String name, String brand,int gasTank){
this.name = name;
this.brand = brand;
this.gasTank = gasTank;
}
public String getname(){
return name;
}
public String getbrand(){
return brand;
}
public int getgasTank(){
return gasTank;
}
public void setname(String name){
this.name = name;
}
public void setbrand(String brand){
this.brand = brand;
}
public void setgasTank(int gasTank){
this.gasTank = gasTank;
}
public double milesPerGallon(double miles, double gallonsUsed){
return miles / gallonsUsed;
}
public String toString(){
return " name: " + name + " Brand: " + brand + " Gallons in Tank: " + gasTank;
}
public double fillTank(double gallonsUsed){
return (gasTank - gallonsUsed);
}
}
class Car extends Vehicle{
int numOfdoors;
int numOfWheels;
public Car(){
this(2,4,"","",10);
}
public Car(int numOfDoors, int numOfWheels, String name, String brand, int gasTank){
this.numOfdoors = numOfDoors;
this.numOfWheels = numOfWheels;
super.name = name;
super.brand = brand;
super.gasTank = gasTank;
}
public int getnumOfdoors(){
return numOfdoors;
}
public int getnumOfWheels(){
return numOfWheels;
}
public void setnumOfdoors(int numOfdoors){
this.numOfdoors = numOfdoors;
}
public double milesPerGallon(double miles, double gallonsUsed){
return miles / gallonsUsed;
}
public String toString(){
return "The car has " + numOfWheels + " wheels and " + numOfdoors + " doors";
}
}
class Bus extends Vehicle {
int numOfWheels;
int numOfPassengers;
public Bus(){
this(1,8,"","", 50);
}
public Bus(int numOfWheels, int numOfPassengers, String name, String brand, int gasTank){
this.numOfWheels = numOfWheels;
this.numOfPassengers = numOfPassengers;
super.name = name;
super.brand = brand;
super.gasTank = gasTank;
}
public int getNumOfWheels(){
return numOfWheels;
}
public int getNumOfPassengers(){
return numOfPassengers;
}
public void setNumOfWheels(int numOfWheels){
this.numOfWheels = numOfWheels;
}
public void setNumOfPassengers(int numOfPassengers){
this.numOfPassengers = numOfPassengers;
}
public double milesPerGallon(double miles, double gallonsUsed){
return miles / gallonsUsed;
}
public String toString(){
return "The bus has "+ numOfWheels + " Wheels and " + numOfPassengers + " Passengers";
}
}
In your code you are overriding the toString method in child classes. While what I understand is that you want to print values from parent also along with child class. So your toString in child class should be like below, where you first call parent toString also.
#Override
public String toString() {
return super.toString() + "wheels " wheels + " doors " + numOfdoors ; // or something like this
}

Objects as arguments

I try to:
Create a Car object in the Main.
Send the object as an argument to the carOwners class.
Print the entire carOwners data from main.
Name and Address will be printed, but not the Car.
What is wrong with my code?
public class TestProgram {
public static void main(String [] args){
Car Saab = createCar();
carOwners guy = createCarOwners (Saab);
printAll(guy);
}
public static Car createCar (){
//user input a, b, c, d
Car temporary = new Car (a, b, c, d);
return temporary;
}
public static carOwners createCarOwners (Car x){
//user input a, b
Car c = x;
carOwners temporary = new carOwners (a, b, c);
return temporary;
}
public static void printAll (carOwners x){
x.printCarData();
x.printNameAddress();
}
}
public class Car {
private String model;
private String Year;
private String licensePlate;
private String color;
public Car (String x, int y, String z, String q){
model = x;
Year = y;
licensePlate = z;
color = q;
}
}
public class carOwners {
private String name;
private String address;
private Car TheCar;
public carOwners (String n, String a, Car b){
name = n;
address = a;
TheCar = b;
}
public void printNameAddress(){
System.out.println();
System.out.println(name);
System.out.println(address);
}
public void printCarData(){
System.out.println(TheCar);
}
}
override toString(), so you can custom the output format of Car
public String toString(){
return "Model :" + this.model + ",Year :" + year;
}
Your Problem is here:
public void printCarData(){
System.out.println(TheCar);
}
You want to print an Object. That doens't work because Java uses the toString-Method for that. If you want to do it like that you have to override the toString()-Method of your car class like that:
public String toString()
{
return "CarModel: " + this.model + ", Production Year: " + year;
}

Getting instance variable from one class using a method in another class?

How would I get the instance variable hitpoints from the Dog class and pass them to the Lion Class through the method eat(X x)?
I'm trying to get the Lion to eat() the Dog and minus points from the instance variable which is stored in a new variable in the Lion Class.
Class Lion
package helloworld;
public class Lion {
public String name;
public int heightCMeters;
public int lengthCMeters;
public float weightKilos;
public int hitPoints;
public Lion(int hitPoints, String name, int heightCMeters, int lengthCMeters, float weightKilos) {
this.name = name;
this.heightCMeters = heightCMeters;
this.lengthCMeters = lengthCMeters;
this.weightKilos = weightKilos;
}
public void lionDetails() {
System.out.println("Name: " + this.name);
System.out.println("Height CM: " + this.heightCMeters);
System.out.println("Length CM: " + this.lengthCMeters);
System.out.println("Weight Kilos: " + this.weightKilos);
}
public void eat(X x) {
int hitPoints = x.hitPoints - 10;
System.out.println(x)
}
}
Class Dog
package helloworld;
public class Dog {
public String name;
public int heightCMeters;
public int lengthCMeters;
public float weightKilos;
public int hitPoints;
public Dog(int hitPoints, String name, int heightCMeters, int lengthCMeters, float weightKilos) {
this.name = name;
this.heightCMeters = heightCMeters;
this.lengthCMeters = lengthCMeters;
this.weightKilos = weightKilos;
}
public void dogDetails() {
System.out.println("Name: " + this.name);
System.out.println("Height CM: " + this.heightCMeters);
System.out.println("Length CM: " + this.lengthCMeters);
System.out.println("Weight Kilos: " + this.weightKilos);
}
public void eat(X x) {
int hitPoints = x.hitPoints - 10;
System.out.println(x)
}
}
Basically, Lions can eat dogs and the converse is true (which is weird, a dog is not brave enough to attack Lions). Anyways, what you need is an abstract class that represents animals that eat animals, this class should contain the hitPoint you mentioned.
abstract class X {
public int hitPoints;
}
// Lions are edible
class Lion extends X{
public void eat(X x) { // pass an edible object
int hitPoints = x.hitPoints - 10;
System.out.println(x)
}
}
//Dogs are edible as well
class Dog extends X{
public void eat(X x) { // pass an edible object
int hitPoints = x.hitPoints - 10;
System.out.println(x)
}
}
And now, for a Lion to a eat dog,
Lion predator = new Lion();
Dog prey = new Dog();
predators.eat(prey); // this passed dog will be eaten
Best way write a test class or write main method for Lion class which will maintain hitpoints of both the classes.
class Test{
public static void main(String[] args){
Dog puppy=new Dog(10,"Moti",12,12,31);
Lion oldLion=new Lion(20,"Old Lion",12,12,43);
oldLion.eat(puppy);
}
}
You must have an abstract class Animal, with all the common methods defined there.
For eat method of Lion class,
public void eat (Animal animal) {
this.hitPoints-=animal.hitPoints;
}
For eat method of Dog class, also the same logic.
Based on the response of sleiman jneidi:
You should create an abstract containing the hitPoints and the eat method (that it's the same behavior for each animal) Then you have not to wrote the method each time
abstract class X {
public int hitPoints;
public void eat(X x) { // pass an edible object
int hitPoints = x.hitPoints - 10;
System.out.println(x)
}
}
// Lions are edible
class Lion extends X{
}
//Dogs are edible as well
class Dog extends X{
}
The instance variable contained in the Animal class is inherited by the Lion and Dog class.
It retains the value each time the eat(Aniamal a) method is called with an Animal object passed as a parameter. So than working on the instance variable contained in the Animal object that has been passed to the eat method we can perform various functions on the instance variable.
public class Animal {
public int hitPoints;
}
public class Lion extends Animal {
public String name;
public Lion(String name) {
this.name = name;
}
public void eat(Animal a) {
a.hitPoints = a.hitPoints - 10;
System.out.println(this.name + " Has: " + a.hitPoints + " HitPoints");
}
}
public class Dog extends Animal {
public String name;
public Dog(String name) {
this.name = name;
}
public void eat(Animal a) {
a.hitPoints = a.hitPoints - 10;
System.out.println(this.name + " Has: " + a.hitPoints + " HitPoints");
}
}
public static void main(String[] args) {
Cat adam = new Cat("adam");
Lion dam = new Lion("dam");
dam.eat(adam);
}
I would make anything that can be eaten implement an interface Edible. Then that interface can have a method isEaten that takes the hit point deduction.
Something like this:
public interface Edible {
void isEaten(final int hitPointsToDeduct);
}
Then your Lion and Dog would implement this so that they could be eaten.
The Dog class would be:
public class Dog implements Edible {
public String name;
public int heightCMeters;
public int lengthCMeters;
public float weightKilos;
public int hitPoints;
public Dog(final int hitPoints, final String name, final int heightCMeters, final int lengthCMeters, final float weightKilos) {
this.name = name;
this.heightCMeters = heightCMeters;
this.lengthCMeters = lengthCMeters;
this.weightKilos = weightKilos;
}
public void dogDetails() {
System.out.println("Name: " + this.name);
System.out.println("Height CM: " + this.heightCMeters);
System.out.println("Length CM: " + this.lengthCMeters);
System.out.println("Weight Kilos: " + this.weightKilos);
}
public void eat(final Edible x) {
x.isEaten(10);
System.out.println(x);
}
public void isEaten(final int hitPointsToDeduct) {
this.hitPoints = this.hitPoints - hitPointsToDeduct;
}
}
And the Lion class:
public class Lion implements Edible {
public String name;
public int heightCMeters;
public int lengthCMeters;
public float weightKilos;
public int hitPoints;
public Lion(final int hitPoints, final String name, final int heightCMeters, final int lengthCMeters, final float weightKilos) {
this.name = name;
this.heightCMeters = heightCMeters;
this.lengthCMeters = lengthCMeters;
this.weightKilos = weightKilos;
}
public void lionDetails() {
System.out.println("Name: " + this.name);
System.out.println("Height CM: " + this.heightCMeters);
System.out.println("Length CM: " + this.lengthCMeters);
System.out.println("Weight Kilos: " + this.weightKilos);
}
public void eat(final Edible x) {
x.isEaten(10);
System.out.println(x);
}
public void isEaten(final int hitPointsToDeduct) {
this.hitPoints = this.hitPoints - hitPointsToDeduct;
}
}
The advantage of this is that the hitPoints field is held centrally to one object. The Lion is not pulling out the value of the Dogs hitPoints. Look at this page for an explanation of the "Tell Dont Ask" concept.
EDIT
Having just had a play, I noticed that you're not setting the hitPoints value in either of your constructors and that your objects print out with the object reference rather than the details. For this, override the toString method. Here's the rewritten bits of the Dog clas:
public Dog(final int hitPoints, final String name, final int heightCMeters, final int lengthCMeters, final float weightKilos) {
this.name = name;
this.heightCMeters = heightCMeters;
this.lengthCMeters = lengthCMeters;
this.weightKilos = weightKilos;
this.hitPoints = hitPoints;
}
#Override
public String toString() {
final StringBuilder builder = new StringBuilder();
builder.append("Name: ");
builder.append(this.name);
builder.append(", Height CM: ");
builder.append(this.heightCMeters);
builder.append(", Length CM: " );
builder.append(this.lengthCMeters);
builder.append(", Weight Kilos: ");
builder.append(this.weightKilos);
builder.append(", Hit Points: ");
builder.append(this.hitPoints);
return builder.toString();
}
So then with this main method:
public static void main(final String[] args) {
final Lion adam = new Lion(500, "Adam", 5, 5, 5);
final Dog fido = new Dog(500, "Fido", 5, 5, 5);
adam.eat(fido);
}
I got the following output:
Name: Fido, Height CM: 5, Length CM: 5, Weight Kilos: 5.0, Hit Points: 490
Notice the hit points have been reduced from 500 to 490.

Categories