How to output an object and its variables - java

Hi I'm trying to create "a class called HotelReport which, when given a Hotel object will produce a short, textual report describing the name of the hotel, the number of rooms and, for each room, lists the number and size of the beds.", but I'm unsure how to add the rooms and number of beds and get the final report to output, any help?
Hotel Class
import java.util.*;
public class Hotel {
// Hotel Name
private String hotelname;
public void setName(String hotelname) {
this.hotelname = hotelname;
}
public String getName() {
return this.hotelname;
}
// Hotel Rooms
private List<String> hotelRooms = new ArrayList<String>();
public void sethotelRooms(List<String> hotelRooms) {
this.hotelRooms = hotelRooms;
}
public List<String> gethotelRooms() {
return hotelRooms;
}
}
Room Class
import java.util.*;
public class Room {
private int roomNumber;
public Room(int roomNumber) {
this.roomNumber = roomNumber;
}
private static List<Bed> beds = new ArrayList<Bed>();
public Room(List<Bed> beds) {
setBeds(beds);
}
public void setBeds(List<Bed> beds) {
this.beds = beds;
}
public List<Bed> getBeds() {
return beds;
}
public String getFormat() {
return String.format("Beds:\t%s\n", getBeds());
}
}
Bed Class
import java.util.ArrayList;
import java.util.*;
public class Bed {
// size of bed
private int singleBed = 1;
private int doubleBed = 2;
// implement single bed
public int getsingleBed() {
return singleBed;
}
public void setsingleBed() {
this.singleBed = singleBed;
}
// implement double bed
public int getdoubleBed() {
return doubleBed;
}
public void setdoubleBed() {
this.doubleBed = doubleBed;
}
}
HotelReport Class
public class HotelReport {
public static void main(String[] args) {
Hotel hotelRooms = new Hotel();
hotelRooms.setName("Intercontinental");
hotelRooms.addRoom(1,2,3)
}
}

Firstly, you'd better add an addRoom() function in Hotel class like this:
public void addBed(Room room){
this.rooms.add(room);
}
Then, override the toString function for each class above.
#override
public String toString(){
String report = "Hotel name:" + this.hotelName;
return report;
}
Use an ArrayList to hold all the instance of Hotel in your main function, and you can use a loop to retrieve them.

Try this:
Hotel class:
class Hotel {
private String name;
private List<Room> rooms = new ArrayList<>();
public void addRoom(Room room) {
rooms.add(room);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<Room> getRooms() {
return rooms;
}
public void setRooms(List<Room> rooms) {
this.rooms = rooms;
}
#Override
public String toString() {
return "Hotel{" +
"name='" + name + '\'' +
", rooms=" + rooms +
'}';
}
}
Room class:
class Room {
private int roomNum;
private List<Bed> beds = new ArrayList<>();
public Room(int roomNum) {
this.roomNum = roomNum;
}
public void addBed(Bed bed) {
beds.add(bed);
}
public int getRoomNum() {
return roomNum;
}
public void setRoomNum(int roomNum) {
this.roomNum = roomNum;
}
public List<Bed> getBeds() {
return beds;
}
public void setBeds(List<Bed> beds) {
this.beds = beds;
}
#Override
public String toString() {
return "Room{" +
"roomNum=" + roomNum +
", beds=" + beds +
'}';
}
}
Bed class
class Bed {
private BedType bedType = BedType.SINGLE;
public Bed() {
}
public Bed(BedType bedType) {
this.bedType = bedType;
}
public BedType getBedType() {
return bedType;
}
public void setBedType(BedType bedType) {
this.bedType = bedType;
}
public enum BedType {
SINGLE, DOUBLE
}
#Override
public String toString() {
return "Bed{" +
"bedType=" + bedType +
'}';
}
}
Finally usage:
public static void main(String[] args) throws Exception {
// beds for room#1
Bed bed1 = new Bed(Bed.BedType.SINGLE);
Bed bed2 = new Bed(Bed.BedType.DOUBLE);
// beds for room#2
Bed bed3 = new Bed(Bed.BedType.SINGLE);
Bed bed4 = new Bed(Bed.BedType.SINGLE);
// Room #1
Room room1 = new Room(1);
room1.addBed(bed1);
room1.addBed(bed2);
// Room #1
Room room2 = new Room(2);
room2.addBed(bed3);
room2.addBed(bed4);
// Hotel
Hotel hotel = new Hotel();
hotel.setName("Intercontinental");
hotel.addRoom(room1);
hotel.addRoom(room2);
}
Get data:
// get the data
String hotelName = hotel.getName();
System.out.println("hotelName = " + hotelName);
List<Room> rooms = hotel.getRooms();
for (Room room : rooms) {
System.out.println("room = " + room);
List<Bed> beds = room.getBeds();
for (Bed bed : beds) {
System.out.println("bed = " + bed);
}
}
Out put:
hotelName = Intercontinental
room = Room{roomNum=1, beds=[Bed{bedType=SINGLE}, Bed{bedType=DOUBLE}]}
bed = Bed{bedType=SINGLE}
bed = Bed{bedType=DOUBLE}
================================
room = Room{roomNum=2, beds=[Bed{bedType=SINGLE}, Bed{bedType=SINGLE}]}
bed = Bed{bedType=SINGLE}
bed = Bed{bedType=SINGLE}
================================

Your code is kind of weird in my opinion. The Hotel class has a field called hotelRooms which is of type ArrayList<String>. Shouldn't it be ArrayList<Room>? That just makes more sense.
And in your Bed class, I am really confused about what you are doing. I think a better implementation would be
public class Bed {
private int bedSize;
//getter and setter for bedSize omitted. I'm lazy
public static final int SIZE_DOUBLE = 2;
public static final int SIZE_SINGLE = 1;
}
You can now set the bed size to double bed like this
yourBed.setBedSize (Bed.SIZE_DOUBLE);
Now that your problems are fixed, let's see how we can turn these objects into String.
To turn an object into a string, you can write a method that returns a String , something like
public String description () {
//blah blah blah
}
However, you better use the toString method in Object for this purpose. Read Effective Java for more info of why you should do this.
#Override
public String toString () {
//blah blah blah
}
And you write a toString method for every class that is related to the hotel. Let's see how the toString methods in each class would look like: (I only show the body cos I'm lazy)
Bed:
if (bedSize == SIZE_DOUBLE)
return "a double bed";
else
return "a single bed";
Room:
return "Room " + Integer.toString (roomNumber);
Hotel:
StringBuilder builder = new StringBuilder ();
builder.append ("A hotel called").append(hotelName).append(".");
builder.append ("It has ").append (hotelRooms.size()).append (" rooms.");
for (Room room : hotelRooms) {
builder.append (room.toString()).append (" has ");
for (Bed bed : room.beds) {
builder.append (bed.toString()).append (" ");
}
builder.append (".");
}
return builder.toString();
Now you can display the hotel's description:
Hotel hotel = new Hotel ();
//do stuff with the hotel, such as setting some of its properties
System.out.println (hotel.toString());

Related

What is the relationship between two classes they are tied to a Third class?

Getting stuck with my Travail System Project, Confusing a little bit about understanding that if there Classes called Bookable, Hotel and BookingSystem.
Hotel class is implements Bookable. Furthermore, BookingSystem Class is composition from Bookable, So, I need to create method at BookingSystem class which called addHotel.
what I must do about it to make a relationship between Hotel Class and BookingSystem Class.
Thanks In Advance.
Israa
Hotal Class:
public class Hotel implements Bookable {
private String name, location;
private int noOfRooms;
private double roomPrice;
private Date bookingDate;
private ArrayList<Integer> bookedRooms = new ArrayList<Integer>();
private ArrayList<Integer> numberOfrooms = new ArrayList<Integer>();
public Hotel() {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public int getNoOfRooms() {
return noOfRooms;
}
public void setNoOfRooms(int noOfRooms) {
this.noOfRooms = noOfRooms;
}
public double getRoomPrice() {
return roomPrice;
}
public void setRoomPrice(double roomPrice) {
this.roomPrice = roomPrice;
}
public Date getBookingDate() {
return bookingDate;
}
public void setBookingDate(Date bookingDate) {
this.bookingDate = bookingDate;
}
public ArrayList<Integer> getBookedRooms() {
return bookedRooms;
}
public void setBookedRooms(ArrayList<Integer> bookedRooms) {
this.bookedRooms = bookedRooms;
}
public String Book() {
if ( numberOfrooms.size() != (bookedRooms.size())) {
for (int i = 0; i < bookedRooms.size(); i++) {
int oldVal = bookedRooms.get(i);
int newVal = oldVal + 1;
bookedRooms.add(bookedRooms.set(i, newVal));
}
}
return null;
}
}
Bookable class:
public interface Bookable {
public String Book();
}
BookingSytsem Class:
public class BookingSystem {
private ArrayList<Customer> customer = new ArrayList<Customer>();
private ArrayList<Bookable> bookable = new ArrayList<Bookable>();
private ArrayList<Operation> operation = new ArrayList<Operation>();
public BookingSystem() {
}
// **
public void addCustomer(String name, int id) {
Customer customers = new Customer(id, name);
customer.add(customers);
System.out.println("new customer " + customers.getName() + " added");
}
// **
public void deleteCustomer(String name, int id) {
Customer customers = new Customer(id, name);
if (customer.contains(name)) {
customer.remove(name);
}
System.out.println("Customer " + customers.getName() + " deleted");
}
public Customer findCustomer(int id) {
for (Customer c : customer) {
if (c.getId() == id) {
return c;
}
}
return null;
}
public void addHotel() {
Hotel H1 = new Hotel();
Scanner name = new Scanner(System.in);
System.out.println("Please Enter the name of Hotel: ");
String n1 = name.nextLine();
bookable.add(H1);
System.out.println("The Hotel " + name + "added");
}
public void makeABooking(Customer c, Bookable b) {
Scanner input =new Scanner(System.in);
System.out.println("Please Enter your name: ");
String name = input.nextLine();
System.out.println("Please Enter your ID: ");
int ID = input.nextInt();
while(true) {
if(ID == -1 && ID == 0) {
System.out.println("Invalid ID. Enter again: ");
name = input.nextLine();
System.out.println("Please Enter your ID: ");
ID = input.nextInt();
}
}
}
}
(Your question is more suitable to https://softwareengineering.stackexchange.com/ - recommend asking it there...)
General speaking it wouldn't make sense to have a Hotel without a name, location or number of rooms so I'd recommend adding a constructor with minimal required information:
public Hotel (String name, String location, int rooms) {
this.name = name;
this.location = location;
this.noOfRooms = rooms;
}
bookingDate makes no sense as a single property of a hotel but rather a property of each booked room so you have a design issue - this is not addressed here.
Again, roomPrice usually varies by room so in a robust solution this would be a property of a room not a hotel - not addressed here.
Why is there a noOfRooms and a numberOfRooms list. In fact, the numberOfRooms list doesn't make sense as a list. I'd just keep the noOfRooms and get rid of numberOfRooms.
An implied property, nbrOfAvailableRooms can be derived from noOfRooms - bookedRooms.size();
I would assume your bookedRooms is a list of room numbers which are booked but that's not possible to tell from your implementation. You should focus on what you want Book to do.
The Book interface method is not documented but it looks like it should simply take an available asset (room) and consider it booked. It should return a boolean success not a String - especially not null.
I recommend writing (in pseudo code) what you want a Book implementation to do - include that in question. That is the core issue you are having.

not sure why i am getting an error for my instance [duplicate]

This question already has answers here:
Java Error: The constructor is undefined
(8 answers)
Closed 3 years ago.
I have created two classes, PassCar and Motor. My project requires that I create a Motor instance for each PassCar, but I am struggling to do so. When I try to create an instance of Motor in PassCar, it does not work.
I've attempted
Motor motor = new Motor();
and
private Motor motor = new Motor();
Below is my code for PassCar
The error states that the constructor Motor is undefined.
public class PassCar extends Vehicle{
private Motor motor = new Motor();// the error
private int numPass;
private boolean AC;
public PassCar(String make, String model, int year, double price, int numPass, boolean aC, Motor motor) {
super(make, model, year, price);
this.numPass = numPass;
AC = aC;
this.motor = motor;
}
public int getNumPass() {
return numPass;
}
public void setNumPass(int numPass) {
this.numPass = numPass;
}
public boolean isAC() {
return AC;
}
public void setAC(boolean aC) {
AC = aC;
}
public Motor getMotor() {
return motor;
}
public void setMotor(Motor motor) {
this.motor = motor;
}
public void description() {
System.out.print("In this application, a passenger car is an every day vehicle registered to an individual");
}
#Override
public String toString() {
String s = super.toString();
s += "PassCar numPass = " + numPass + ", AC = " + AC + ", motor = " + motor;
return s;
}
}
code for Motor class
public class Motor {
private String name;
private int cylinders;
private int bhp;
private double displacement;
public Motor(String name, int cylinders, int bhp, double displacement) {
super();
this.name = name;
this.cylinders = cylinders;
this.bhp = bhp;
this.displacement = displacement;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getCylinders() {
return cylinders;
}
public void setCylinders(int cylinders) {
this.cylinders = cylinders;
}
public int getBhp() {
return bhp;
}
public void setBhp(int bhp) {
this.bhp = bhp;
}
public double getDisplacement() {
return displacement;
}
public void setDisplacement(double displacement) {
this.displacement = displacement;
}
#Override
public String toString() {
return "Motor name = " + name + ", cylinders = " + cylinders + ", bhp = " + bhp + ", displacement = " + displacement;
}
}
code to print information entered
public class VehicleTest {
public static void main(String[] args) {
PassCar p1 = new PassCar("Ford", "Mustang", 2016, 44500.0, 5, true, "EcoBoost", 6, 310, 2.3);
System.out.print(p1);
}
}
The issue is here
public Motor(String name, int cylinders, int bhp, double displacement) {
super();
this.name = name;
this.cylinders = cylinders;
this.bhp = bhp;
this.displacement = displacement;
}
You've created a constructor that takes some argument but you're trying to call the constructor with no arguments here
private Motor motor = new Motor(); //cant find constructor that takes no arguments
To fix the issue you have to declare a constructor with no arguments along with your other one.
public Motor(){
//code here
}
Try adding the following code in the Motor classs
public Motor(){
}
Add the empty parameter constructor to your Motor class. Like this;
public Motor() {
}

Printing data of departments

When I try to print out the data within departments, it prints only the memory of their address.
How can I print the departments and the data?
I want the College department to get all the parameters that are in the Lecturer department. That means that when I create a new College I want it to create a new Lecturer with all the parameters inside.
In College class, I added a method (NewLecturer) that adds an additional Lecturer. Is it written correctly?
public class main {
public static void main(String[] args) {
Lecturer[] L1 = new Lecturer[] { new Lecturer("Dani", 2, "Banana", 1001) };
College FirstCollege = new College("Hmpson", 2, L1);
for (int i = 0; i < L1.length; i++) {
System.out.print(L1[i]);
}
System.out.print(L1);
System.out.print(FirstCollege);
}
}
First class:
public class Lecturer {
public String nameOfLecturer = "";
public int numOfTimesPenFalls = 0;
public String favoriteIceCream = "";
public int numAuto = 1000;
//constructors, same name like class
public Lecturer(String name, int TimesPenFalls, String IceCream, int num) {
nameOfLecturer = name;
numOfTimesPenFalls = TimesPenFalls;
favoriteIceCream = IceCream;
numAuto = num;
int maxLecturer = 10;
}
//Copy constructor
public Lecturer(Lecturer other) {
nameOfLecturer = other.nameOfLecturer;
numOfTimesPenFalls = other.numOfTimesPenFalls;
favoriteIceCream = other.favoriteIceCream;
numAuto = other.numAuto;
}
}
Second class:
public class College {
public String CollegeName = "";
public int numOfLecturers = 0;
public Lecturer[] allLecturers;
// constructors, same name like class
public College(String name, int numLecturers, Lecturer[] dataBase) {
CollegeName = name;
numOfLecturers = numLecturers;
allLecturers = dataBase;
int maxLecturer = 10;
}
// getter, only private
public String getCollegeName() {
return CollegeName;
}
// setter, only private
public void setCollegeName(String newcollegeName) {
CollegeName = newcollegeName;
}
public boolean newLecturer(Lecturer addNewLecturer, int maxLecturer) {
if (numOfLecturers < maxLecturer || numOfLecturers == maxLecturer) {
numOfLecturers += 1;
return true;
} else {
System.out.print("Sorry, Max Lecturer!");
return false;
}
}
public void sortLecturer(Lecturer[] arrAllLecturers) {
int numOfTimesPenFalls = 0;
}
}
System.out.print(Object) will call the toString() method of the parameter Object.
The default toString method of Object gives you nothing interesting, so you will have to override toString to fit your needs, for example :
In class Lecturer :
#Override
public String toString() {
return "Lecturer [nameOfLecturer=" + nameOfLecturer + ", numOfTimesPenFalls=" + numOfTimesPenFalls
+ ", favoriteIceCream=" + favoriteIceCream + ", numAuto=" + numAuto + "]";
}
In class College :
#Override
public String toString() {
return "College [CollegeName=" + CollegeName + ", numOfLecturers=" + numOfLecturers + ", allLecturers="
+ Arrays.toString(allLecturers) + "]";
}
create setter / getter and toString method for your Lecturer and College classes.

Why does the toString Method not work when it is overwritten?

public abstract class Car {
// This class includes common properties for a car, in this way we wont have to change if we need to add a new car brand
public String name;
public String colour;
public int model;
public String feature;
public String getFeature() {
return feature;
}
public void setFeature(String feature) {
this.feature = feature;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getColour() {
return colour;
}
public void setColour(String colour) {
this.colour = colour;
}
public int getModel() {
return model;
}
public void setModel(int model) {
this.model = model;
}
}
Test.java
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
CarFactory carfactory = new CarFactory();
System.out.println("Hello, please enter your car brand \n BMW \n MERCEDE \n OPEL");
Car usercar = null;
String usertext = input.nextLine();
usercar = carfactory.makeCar(usertext);
System.out.println("enter colour of your car");
usertext = input.nextLine();
usercar.setColour(usertext);
System.out.println("enter model of your car");
usertext =input.nextLine();
usercar.setModel(Integer.parseInt(usertext));
System.out.println("Your Car Information;\n "+ usercar.getName()+" \n Colour:" + usercar.getColour() + "\n Model "+ usercar.getModel()+ "\n Your car's plus point is " + usercar.getFeature());
}
The question is, if i want to print car information with toString Metod, how would it be? i wrote one in Car class but it didnt work, feature is assign from car's own classes..
here is the my toString metod
public String toString(){
return "Your Car Information;\n "+ getName()+" \n Colour:" + getColour() + "\n Model "+getModel()+ "\n Your car's plus point is " +getFeature();
}
Firstly, you must override toString() method of java.lang.Object like this:
class Car {
...
#Override
public String toString() {
return "Your Car Information;\n " + getName() + " \n Colour:" +
getColour() + "\n Model " + getModel() + "\n Your car's plus point is " +
getFeature();
}
}
Secondly, you can use it like this:
public static void main(String[] args) {
// 'CarClass' is a no-abstract class, who extends the 'Car' class
Car car = new CarClass();
// the first way
String information = car.toString();
System.out.println(information);
// the second way
System.out.println(car);
}

I am getting "Exception in thread "main" java.lang.NullPointerException even though no values are set to null

public class ParkedCar {
private String make;
private String model;
private String color;
private String licenseNum;
public ParkedCar(String make, String model, String color, String licenseNum) {
this.make = make;
this.model = model;
this.color = color;
this.licenseNum = licenseNum;
}
public void setMake(String ma) {
make = ma;
}
public void setModel(String mo) {
model = mo;
}
public void setColor(String c) {
color = c;
}
public void setLicenseNum(String ln) {
licenseNum = ln;
}
public String getMake() {
return make;
}
public String getModel() {
return model;
}
public String getColor() {
return color;
}
public String getLicenseNum() {
return licenseNum;
}
}
public class ParkingMeter {
private ParkedCar parkedcar;
private int timePurchased;
private int timeParked;
public ParkingMeter(ParkedCar parkedcar, int timePurchased, int timeParked) {
this.parkedcar = parkedcar;
this.timePurchased = timePurchased;
this.timeParked = timeParked;
}
/*public ParkingMeter (ParkedCar parkedcar) {
this.parkedcar = null;
}*/
public void setTimePurchased(int timePurchased) {
this.timePurchased = timePurchased;
}
public int getTimePurchased() {
return timePurchased;
}
public void setTimeParked(int timeParked) {
this.timeParked = timeParked;
}
public int getTimeParked() {
return timeParked;
}
public int TimeExpired() {
if (timeParked > timePurchased)
return timeParked - timePurchased;
else
return 0;
}
public String toString() {
return "Make: " + parkedcar.getMake() + "\nModel: " + parkedcar.getModel() + "\nColor: " + parkedcar.getColor() + "\nLicense Number: " + parkedcar.getLicenseNum();
}
}
public class ParkingTicket {
private ParkingMeter parkingmeter;
public ParkingTicket(ParkingMeter parkingmeter) {
this.parkingmeter = parkingmeter;
}
public int TicketCost() {
if (parkingmeter.getTimeParked() > parkingmeter.getTimePurchased()) {
if (parkingmeter.getTimeParked() <= 60)
return 25;
else
return 25 + (10*(parkingmeter.TimeExpired())/60);
}
else
return 0;
}
}
public class PoliceOfficer {
private String OfficerName;
private int OfficerNum;
private ParkingMeter pm;
private ParkingTicket pt;
public PoliceOfficer(ParkingTicket pt, String OfficerName, int OfficerNum) {
this.OfficerName = OfficerName;
this.OfficerNum = OfficerNum;
}
public void setOfficerName(String OfficerName) {
this.OfficerName = OfficerName;
}
public void setOfficerNum(int OfficerNum) {
this.OfficerNum = OfficerNum;
}
public String getOfficerName() {
return OfficerName;
}
public int getOfficerNum() {
return OfficerNum;
}
public boolean isExpired() {
if (pm.getTimeParked() > pm.getTimePurchased())
return true;
else
return false;
}
public String toString() {
return "Officer Name: " + OfficerName + "\nOfficer Number: " + OfficerNum + "\n" + "\nFine: " + pt.TicketCost();
}
}
public class ParkingTicketDemo {
public static void main(String[] args) {
ParkedCar pc = new ParkedCar("Toyota", "Camry", "Blue", "BXZ 152");
System.out.println(pc);
ParkingMeter pm = new ParkingMeter(pc, 60, 120);
ParkingTicket pt = new ParkingTicket(pm);
PoliceOfficer po = new PoliceOfficer(pt, "Roger", 337);
System.out.println(po);
}
}
I have been trying to create a program to create and issue a parking ticket and have run into the problem where it compiles, but when it runs it gives out the error message Exception in thread "main" java.lang.NullPointerException. I am a fairly new programmer and this is the first time I have encountered the problem so I have yet fully understand it and cannot seem to fix it. i have tried reading other things online, but just do not understand I would love a simple explaination to my problem.
The NPE happens because of these two lines:
PoliceOfficer po = new PoliceOfficer(pt, "Roger", 337);
System.out.println(po);
In your constructor for PoliceOfficer, you don't do anything with the ParkingTicket instance pt.
public PoliceOfficer(ParkingTicket pt /* not set anywhere */, String OfficerName, int OfficerNum) {
this.OfficerName = OfficerName;
this.OfficerNum = OfficerNum;
}
The fields ParkingMeter pm and ParkingTicket pt remain null since you haven't initialized them.
Then you try to print the object: System.out.println(po); What this does is call toString() on po, it is equivalent to this:
System.out.println(po.toString());
Now because your toString()
public String toString() {
return "Officer Name: " + OfficerName + "\nOfficer Number: " + OfficerNum + "\n" + "\nFine: " + pt.TicketCost();
}
uses the pt, it creates a NullPointerException, since pt is null.
Since you are already passing a ParkingTicket instance into the constructor for PoliceOfficer, use that instance to assign its member variable pt.

Categories

Resources