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;
}
Related
I have a info class Vehicle that has multiple attributes and I have a Moped info class that extends the vehicle class. I need to create a main program that I can add multiple mopeds to an array list and then print them. Here is my attempt:
info class1:
package data;
public class Vehicle {
private float price;
private String color;
private int maximumSpeed;
public float getPrice() {
return price;
}
public void setPrice(float price) {
this.price = price;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color= color;
}
public int getMaximumSpeed() {
return maximumSpeed;
}
public void setMaximumSpeed(int maximumSpeed) {
this.maximumSpeed = maximumSpeed;
}
public String toString() {
return "Price: "+this.price+" Color: "+this.color+" Maximum speed: "+this.maximumSpeed;
}
}
Info class2:
package data;
public class Moped extends Vehicle{
private String Brand;
private String type;
public String getBrand() {
return brand;
}
public void setBrand(String brand) {
this.brand= brand;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String toString() {
return "Brand: "+this.brand+" Type: "+this.type;
}
}
Main program:
package app;
import java.util.ArrayList;
import java.util.Scanner;
import data.*;
public class ExtendsTest {
public static void main(String[] args) {
ArrayList<Moped> list=new ArrayList<>();
Moped mp=new Moped();
askForMopedInfo(mp);
lista.add(mp);
printMoped(list);
}
private static void printMoped(ArrayList<Moped> list) {
for (int i=0;i<list.size(); i++) {
System.out.println(list.get(i));
}
}
private static void askForMopedInfo(Moped mp) {
Scanner scanner = new Scanner(System.in);
System.out.print("Brand: ");
String k = scanner.nextLine();
mp.setBrad(k);
System.out.print("Type: ");
k = scanner.nextLine();
mp.setType(k);
System.out.print("Price: ");
int k1 = Integer.parseInt(scanner.nextLine());
mp.setPrice(k1);
System.out.print("Color: ");
k = scanner.nextLine();
mp.setColor(k);
System.out.print("Maximum speed: ");
k1 = Integer.parseInt(scanner.nextLine());
mp.setMaximumSpeed(k1);
}
}
When I run the program I get asked for:
Brand:
Type:
Price:
Color:
Maximum speed:
But the program only prints:
Brand: x Type: x
And I am still not sure how to add multiple mopeds to the array list. Any help would be much appreciated!
Update toString method of your Moped class, like this:
package data;
public class Moped extends Vehicle {
/*
other code
*/
public String toString() {
return super.toString() +" Brand: "+this.brand+" Type: "+this.type;
}
}
to Add more mopeds to the array list, you can do this:
public static void main(String[] args) {
ArrayList<Moped> list=new ArrayList<>();
While(true){
Moped mp=new Moped();
askForMopedInfo(mp);
list.add(mp);
printMoped(list);
}
}
I need to write up a static method that takes an array of Vehicles and print each registration number in the array. The object in the array is either a Vehicle, a Car, or a Truck object reference. Finally, I need to print the registration number of the object on a single line on its own.
So the code is:
public class Vehicle {
private String registrationNumber;
public Vehicle(String rego) {
registrationNumber = rego;
}
public String getRegistrationNumber() {
return registrationNumber;
}
}
public class Car extends Vehicle {
int passengers;
public Car(String rego, int pass) {
super(rego);
passengers = pass;
}
public int getPassengers() {
return passengers;
}
}
public class Truck extends Vehicle {
int tons;
public Truck(String rego, int tons) {
super(rego);
this.tons = tons;
}
public int getTons() {
return tons;
}
}
I have to write up a static method for the following test and get the following, but I am having some trouble.
Test and expected Result
This is what I have done so far:
public static void printRegNum(Vehicle[] list){
for (int i = 0; i < list.length; i++){
System.out.println(list[i]);
}
}
The 1st way to play with your System.out.println(list[i]); is to override the toString() method in class Vehicle:
public class Vehicle {
private String registrationNumber;
public Vehicle(String rego) {
registrationNumber = rego;
}
public String getRegistrationNumber() {
return registrationNumber;
}
public String toString() {
return registrationNumber;
}
}
The 2nd way is change:
from:
System.out.println(list[i]);
to:
System.out.println(list[i].getRegistrationNumber());
Hope those can help.
Not getting where's the problem
i.e.
public static void main(String[] args){
Car car = new Car("MYCAR",4);
Truck t = new Truck("MYTRUCK", 16);
Vehicle[] myList = new Vehicle[] {car, t};
printRegNum(myList);
}
Also seems that you only need to print the "rego".
System.out.println(list[i].getRegistrationNumber());
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;
}
So it seems like I have to make an object array of a sub-class (Bicycle).
I then add two objects to this.. and loop the array and print what each object is constructed from.
This sounds thoroughly confusing to me, and I'm unsure how to go about this.
I'll also post the rest of my code, to make more sense.
MAIN:
package javaapplication4;
public class JavaApplication4 {
public static void main(String[] args) {
Bicycle myBike = new Bicycle(1, "Haro BMX", true, "Handlebars, Tyres, Frame");
System.out.println(myBike);
}
}
package javaapplication4;
public class Implement {
String name;
boolean hasMovingParts;
String constructedFrom;
public Implement() {
}
public Implement(String name, boolean hasMovingParts, String constructedFrom) {
this.name = name;
this.hasMovingParts = hasMovingParts;
this.constructedFrom= constructedFrom;
}
public String getName() {
return name;
}
public boolean getMovingParts() {
return hasMovingParts;
}
public String getConstructedFrom(){
return constructedFrom;
}
public class Bicycle extends Implement {
public int seatNumber;
public Bicycle(int seatNumber, String name, boolean hasMovingParts, String constructedFrom) {
this.seatNumber = seatNumber; //takes the value you pass as parameter
this.name = name; // and stores it into the instance variable
this.hasMovingParts = hasMovingParts;
this.constructedFrom = constructedFrom;
}
#Override
public String toString(){
return String.format("*Vehicle Statistics* Seats: %d, Name:" +
" %s, Contains Moving Parts: %b, Materials: %s",
seatNumber, name, hasMovingParts, constructedFrom);
}
}
}
package javaapplication4;
public class Bicycle extends Implement {
public int seatNumber;
public Bicycle(int seatNumber, String name, boolean hasMovingParts, String constructedFrom) {
this.seatNumber = seatNumber;
this.name = name;
this.hasMovingParts = hasMovingParts;
this.constructedFrom = constructedFrom;
}
#Override
public String toString() {
return String.format("*Vehicle Statistics* Seats: %d, Name:" +
" %s, Contains Moving Parts: %b, Materials: %s",
seatNumber, name, hasMovingParts, constructedFrom);
}
}
Change your main method to create an array of Bicycles, then add them by the index :
public static void main(String[] args) {
Bicycle[] bicycles = new Bicycle[2];
bicycles[0] = new Bicycle(1, "Haro BMX", true, "Handlebars, Tyres, Frame");
bicycles[1] = new Bicycle(1, "Orah XMB", true, "Handlebars, Tyres, Frame");
for (Bicycle bicycle : bicycles){
System.out.println(bicycle);
}
}
Expected Result of code is ClassCastException but Actual Result :- [Person with pid- 1 - a1-name, Person with pid- 2 - c2-name, Sorting.Employee#cdfc9c, Sorting.Employee#1837697]
Person class:
package Sorting;
public class Person implements Comparable<Person> {
private int pid;
private String pname;
public int getPid() {
return pid;
}
public void setPid(int pid) {
this.pid = pid;
}
public String getPname() {
return pname;
}
public void setPname(String pname) {
this.pname = pname;
}
#Override
public String toString() {
return "Person with pid- " + getPid() + " - " + getPname();
}
#Override
public int compareTo(Person p) {
return this.pid - p.pid;
}
}
Employee class:
package Sorting;
public class Employee implements Comparable {
#Override
public int compareTo(Object o) {
return 0;
}
}
SortingofObjects class:
package Sorting;
import java.util.ArrayList;
import java.util.Collections;
public class SortingofObjects {
public static void main(String[] args) {
Person p1 = new Person();
p1.setPid(1);
p1.setPname("a1-name");
Person p2 = new Person();
p2.setPid(2);
p2.setPname("c2-name");
Employee e1 = new Employee();
Employee e2 = new Employee();
ArrayList a = new ArrayList();
a.add(p1);
a.add(p2);
a.add(e1);
a.add(e2);
Collections.sort(a);
System.out.println(a);
}
}
Collections.sort does not call compareTo on every pair in the List, just enough pairs to sort the List. As an example, run this code:
public class Test implements Comparable<Test> {
public static void main(String[] args) {
List<Test> list = new ArrayList<Test>();
list.add(new Test(1));
list.add(new Test(2));
list.add(new Test(3));
list.add(new Test(4));
Collections.sort(list);
}
private final int number;
Test(int number) {
this.number = number;
}
#Override
public int compareTo(Test that) {
System.out.println(this + ".compareTo(" + that + ")");
return 0;
}
#Override
public String toString() {
return "" + number;
}
}
The output is
2.compareTo(1)
3.compareTo(2)
4.compareTo(3)
Since your List is in the order Person, Person, Employee, Employee, the only combination that would throw a ClassCastException, namely
Person.compareTo(Employee)
never occurs. If your List contained an Employee before a Person it would throw an exception.
If it just so happens that the sorting algorithm used only compares Employees to Persons, and not the other way around, then it'll never throw, because Employee.compareTo accepts any Object. You just got lucky, more or less.