Objects as arguments - java

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

Related

Java Array storing objects with multiple fields

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

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.

Keep getting "null has 00null"

Im working with a stand-alone class, and a main driver, here's the stand-alone class:
public class Bugs{
private String bugType;
private int legs;
private int arms;
private String nativeTo;
public Bugs(String bt, int l, int a, String nt){
bt=bugType;
l=legs;
a=arms;
nt=nativeTo;
}
public Bugs(String bt, int l, int a){
bt=bugType;
l=legs;
a=arms;
nativeTo="Not known";
}
public String getbt(){
return bugType;
}
public void setbugType(String bugType){
this.bugType=bugType;
}
public int getlegs(){
return legs;
}
public void setlegs(int legs){
this.legs=legs;
}
public int getarms(){
return arms;
}
public void setarms(int arms){
this.arms=arms;
}
public String getnativeTo(){
return nativeTo;
}
public void setnativeTo(String nativeTo){
this.nativeTo=nativeTo;
}
public String toString(){
return bugType + " has " + legs + arms + nativeTo;
}
}
And here's the main driver:
public class myBugs{
public static void main (String args[]){
Bugs asiaBeetle = new Bugs("Asian Beetle", 2, 2, "Japan");
Bugs spider = new Bugs("Spider", 1000, 0);
Bugs americanBeetle = new Bugs("American Beetle", 2, 2, "USA");
System.out.println(asiaBeetle);
}
}
JGRASP keeps returning "null has 00null", every time I run the main driver. What am I doing wrong?
Swap your assignments in your constructors :
public Bugs(String bt, int l, int a, String nt){
bugType = bt;
legs = l;
arms = a;
nativeTo = nt;
}
You have to do the same for the other :
public Bugs(String bt, int l, int a){
bugType = bt;
legs = l;
arms = a;
nativeTo="Not known";
}
Change your constructor to this offcourse do the same for the other as well
public Bugs(String bt, int l, int a, String nt){
bugType=bt;
legs=l;
arms=a;
nativeTo= nt;
}

Adding objects to ArrayList from another class

I'm very new to programming and currently trying to write a car showroom application. I've got a vehicle class, showroom class and I'm trying to use a showroom driver for the input.
I'm having problems adding vehicle objects to my arraylist. Could someone point me in the correct direction.
My code:
public class Vehicle {
private String manufacturer;
private String model;
private String custName;
private String vin;
private String dateMan;
private String dateSold;
private Boolean sold;
private char tax;
private double cost;
public Vehicle(String a, String b, String c, String d) {
manufacturer = a;
model = b;
vin = c;
dateMan = d;
}
public String toString() {
String s = "Manufacturer: " + manufacturer + " Model: "
+ model + " vin: " + vin + "Date Manufactured:" + dateMan
+ "Cost: " + cost;
return s;
}
public void buyVehicle(String a, String b) { //buy method for the vehicle
a = dateSold;
b = custName;
sold = true;
}
public String getManufacturer() {
return manufacturer;
}
public String getModel() {
return model;
}
public String getCustName() {
return custName;
}
public String getVin() {
return vin;
}
public String getDateMan() {
return dateMan;
}
public String getDateSold() {
return dateSold;
}
public Boolean getSold() {
return sold;
}
public char getTax() {
return tax;
}
public double getCost() {
return cost;
}
}
.
import java.util.ArrayList;
public class Showroom {
private ArrayList<Showroom> theVehicles;
public Showroom() {
theVehicles = new ArrayList<Showroom>();
}
public boolean addVehicle(Showroom newVehicle) {
theVehicles.add(newVehicle);
return true;
}
}
.
import java.util.*;
public class ShowroomDriver {
public static void main(String[] args) {
Vehicle v1 = new Vehicle("renault", "clio", "12", "290890");
Showroom.addVehicle(v1);
}
}
Basically, I'm confused to how I add vehicle objects to the arraylist within the showroom class. If anyone could point me in the right direction I would really appreciate it.
Thanks in advance.
You have to instantiate the class Showroom to use its properties and methods
The collection theVehicles is of Vehicle not Showroom.
package cars;
import java.util.ArrayList;
import java.util.List;
public class Showroom {
private final List<Vehicle> theVehicles = new ArrayList<>();
public boolean addVehicle( Vehicle newVehicle ) {
theVehicles.add( newVehicle );
return true;
}
public static void main( String[] args ) {
final Showroom showroom = new Showroom();
final Vehicle v1 = new Vehicle( "renault", "clio", "12", "290890" );
showroom.addVehicle( v1 );
}
}
in Vehicle class, a mistake around '=' operator, I suppose you want to memorize the sold value and the customer name:
public void buyVehicle( String a, String b ) { // buy method for the vehicle
dateSold = a;
custName = b;
sold = true;
}
I Think this
private ArrayList <Showroom> theVehicles;
Shoulde be this
private ArrayList <Vehicle> theVehicles;
theVehicles = new ArrayList <Vehicle> ();
And this
public boolean addVehicle( Showroom newVehicle )
Should be
public boolean addVehicle( Vehicle newVehicle )
Don't you want an ArrayList of Vehicles and not ShowRooms?
Your problem is that you declared an ArrayList of ShowRoom objects, but what you want is an ArrayList of Vehicle objects.
private ArrayList<Vehicle> theVehicles;
public boolean addVehicle(Vehicle v) {
theVehicles.add(v);
return true;
}

printing out data of array element in java

If I have an array of a class type (cars) and each car has been given a make and model
using set methods, how can I then print out the make and model of a particular element?
I need to print this out in a separate class
public class Car {
private String make;
private String model;
public void setMake (String str1) {
make = str1;
}
public void setModel (String str2) {
model = str2;
}
You need to add a toString() method to your class
public class Car {
private String make;
private String model;
public void setMake (String str1) {
make = str1;
}
public void setModel (String str2) {
model = str2;
}
#Override
public String toString() {
return "Make :"+ make + " Model :" + model;
}
}
Just printing a car
You can then use this as follows
public static void main(String[] args){
Car car=new Car();
car.setMake("Audi");
car.setModel("ModelName");
System.out.println(car);
}
Printing all of an array
Equally if this exists in an array of cars (I'm using the constructor I introduce in the notes for brevity)
public static void main(String[] args){
Car[] cars=new Car[3];
cars[0]=new Car("Audi","ModelName");
cars[1]=new Car("BMW","ModelName");
cars[2]=new Car("Honda","ModelName");
for(int i=0;i<cars.length;i++){
System.out.println(cars[i]);
}
}
Printing after user selects an index
public static void main(String[] args){
Car[] cars=new Car[3];
cars[0]=new Car("Audi","ModelName");
cars[1]=new Car("BMW","ModelName");
cars[2]=new Car("Honda","ModelName");
Scanner scan=new Scanner(System.in);
System.out.println("Select index to print, should be between 0 and " + (cars.length-1));
//checks that user actually inputs an integer,
//checking its in range is left as an excercise
while (scan.hasNextInt()==false){
scan.next(); //consume bad input
System.out.println("Select index to print, should be between 0 and " + (cars.length-1));
}
int index=scan.nextInt();
System.out.println(cars[index]);
}
Notes
It seems like the make and model are essential to the workings of the car class, consider changing your constructor to take them as arguments
public Car(String make, String model){
this.make=make;
this.model=model;
}
All this assumes you already have the element you wish to print
class Car{
String make ;
String model;
#Override
public String toString() {
return "make :"+ this.make + " model :" + this.model;
}
}
List<Car> list= new ArrayList<Car>();
Car c1=new Car();
Car c2=new Car();
Car c3=new Car();
Car c4=new Car();
list.add(c1);
list.add(c2);
list.add(c3);
list.add(c4);
for(Car car : list)
{
System.out.println(car);
}
public class Car {
private String make;
private String model;
public Car(String make, String model) {
this.make = make;
this.model = model;
}
public void setMake (String str1) {
make = str1;
}
public void setModel (String str2) {
model = str2;
}
public String getMake() {
return make;
}
public String getModel() {
return model;
}
}
public class PrintCars {
public static void main(String []args) {
Car cars[] = new Car[10];
// Assume you populate the array with Car objects here by code
cars[0] = new Car("make1", "model1");
for (Car carObj : cars) {
System.out.println(carObj.getmake());
System.out.println(carObj.getmodel());
}
}
}
Try this
private static String toString(sample[] carTypes)
{
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < carTypes.length; i++)
{
if (carTypes[i] != null)
{
stringBuilder.append(" Name : ");
stringBuilder.append(carTypes[i].name);
stringBuilder.append(",");
stringBuilder.append(" Model : ");
stringBuilder.append(carTypes[i].model);
stringBuilder.append(",");
}
}
return stringBuilder.toString().substring(0, stringBuilder.toString().length() - 1);
}
output :
Name : BMW, Model : Mark 3, Name : AUDI, Model : A-6, Name : BENZ, Model : BZ

Categories