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);
}
Related
I am trying to code a song using polymorphism, but I am quite new to Java coding and have a really basic experience. I could use some help with the classes, but my biggest problem is that I do not know how to write the main part of the code, I'd be very grateful if someone could help me with it.
Here is what I have so far
public class OldMacdonald {
public interface Farm{
public String getName();
public String getNoise();
}
class Dog implements Farm{
String name;
String noise;
public Dog(String name, String noise) {
name=name;
noise=noise;
}
public String getName() {
return name;
}
public String getNoise() {
return noise;
}
}
class Cat implements Farm{
String name;
String noise;
public Cat(String name, String noise) {
name=name;
noise=noise;
}
public String getName() {
return name;
}
public String getNoise() {
return noise;
}
}
class Duck implements Farm{
String name;
String noise;
public Duck(String name, String noise) {
name=name;
noise=noise;
}
public String getName() {
return name;
}
public String getNoise() {
return noise;
}
}
class Cow implements Farm{
String name;
String noise;
public Cow(String name, String noise) {
name=name;
noise=noise;
}
public String getName() {
return name;
}
public String getNoise() {
return noise;
}
}
class Pig implements Farm{
String name;
String noise;
public Pig(String name, String noise) {
name=name;
noise=noise;
}
public String getName() {
return name;
}
public String getNoise() {
return noise;
}
}
class Song{
private Farm [] animal = new Farm[5];
Song() {
animal[0] = new Dog("dog", "woof");
animal[1] = new Cat("cat", "meow");
animal[2] = new Duck("duck", "quack");
animal[3] = new Cow("cow", "moo");
animal[4] = new Pig("pig", "oink");
}
public void lyrics() {
int i;
for(i=0; i<animal.length; i++) {
System.out.println("Old MacDonald had a farm, E I E I O,\r\n" +
"And on his farm he had a " + animal[i].getName() + ", E I E I O.\r\n" +
"With a " + animal[i].getNoise() + " " + animal[i].getNoise() + " here and a " + animal[i].getNoise() + " " + animal[i].getNoise() + " there,\r\n" +
"Here a " + animal[i].getNoise() + ", there a " + animal[i].getNoise() + ", evrywhere a " + animal[i].getNoise() + " " + animal[i].getNoise() + ".\r\n" +
"Old MacDonald had a farm, E I E I O.\r\n\r\n");
}
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
}
}
You need to "launch" your code somehow, in a Java standalone program like this that would be done from the main method:
public static void main(String[] args)
It looks like Song is your class that actually starts everything off so you need to create an instance of that:
public static void main(String[] args) {
Song mySong = new Song();
}
The lyrics are output by the lyrics() method, so we need to call that:
public static void main(String[] args) {
Song mySong = new Song();
mySong.lyrics();
}
You'll want to tweak your Song() constructor method too:
public Song() {
You might want to update your constructors in animal classes too, you were assigning the parameter to itself (easily done when using same names for variables in params and private fields):
public Cat(String name, String noise) {
this.name = name;
this.noise = noise;
}
If I understood you correctly, in your main()method you just have to create an instance of Song and call lyrics() on it, no? That will populate the Farm array with the animals and call the appropriate methods when printing the lyrics.
The current code prints the statements individually whereas I want to string all the variables regarding the car together (colour, number of cylinders, and number of seats) and string all the variables regarding the truck together (colour, number of cylinders, and towing capacity). The variable seats is in the subclass Car and prints its own independent statement and the variable towing capacity is in the subclass Truck which also prints its own statement. I want all the variables for the car in one sentence and all the variables for the truck in one sentence.
import java.util.Scanner;
class Vehicle {
Scanner s = new Scanner(System.in);
private String color;
private int noOfCylinders;
public int noOfSeats;
public int towingCapacity;
public Vehicle() {
color = "Black";
noOfCylinders = 0;
noOfSeats = 1;
towingCapacity =0;
}
public Vehicle(String color, int noOfCylinders, int noOfSeats, int towingCapacity) {
this.color = color;
this.noOfCylinders = noOfCylinders;
this.noOfSeats = noOfSeats;
this.towingCapacity = towingCapacity;
}
public void setColor() {
System.out.print("Enter color of vehicle: ");
color = s.nextLine();
}
public String getColor() {
return color;
}
public void setNoOfCylinders() {
System.out.print("Enter number of cylinders: ");
noOfCylinders = s.nextInt();
}
public int getNoOfCylinders() {
return noOfCylinders;
}
public void setNoOfSeats() {
System.out.print("Enter numer of seats: ");
noOfSeats = s.nextInt();
}
public void setTowingCapacity() {
System.out.print("Enter towing Capacity: ");
towingCapacity = s.nextInt();
}
public String toString() {
String information;
information = "is " + color + " and it has " + noOfCylinders + " cylinders.";
return information;
}
}
public class CreateVehicle {
public static void main(String[] args) {
Car CarObject = new Car();
Truck TruckObject = new Truck();
CarObject.getColor();
CarObject.setColor();
CarObject.getNoOfCylinders();
CarObject.setNoOfCylinders();
CarObject.toString();
CarObject.setNoOfSeats();
TruckObject.getColor();
TruckObject.setColor();
TruckObject.getNoOfCylinders();
TruckObject.setNoOfCylinders();
TruckObject.toString();
TruckObject.setTowingCapacity();
CarObject.toStringSeats();
TruckObject.toStringCapacity();
System.out.print(("\nThe car ")+CarObject.toString());
System.out.print(("\nThe truck ")+TruckObject.toString());
}
}
class Car extends Vehicle{
public void toStringSeats(){
System.out.print("\nThe car has " + noOfSeats + " seats.");
}
}
class Truck extends Vehicle {
public void toStringCapacity() {
System.out.print("\nThe truck has a towing capacity of " + towingCapacity + ".");
}
}
you don't need some code as I have commented the same below.
Use the toString methods as given below.
public class CreateVehicle {
public static void main(String[] args) {
Car CarObject = new Car();
Truck TruckObject = new Truck();
//CarObject.getColor();
CarObject.setColor();
// CarObject.getNoOfCylinders();
CarObject.setNoOfCylinders();
//CarObject.toString();
CarObject.setNoOfSeats();
//TruckObject.getColor();
TruckObject.setColor();
//TruckObject.getNoOfCylinders();
TruckObject.setNoOfCylinders();
//TruckObject.toString();
TruckObject.setTowingCapacity();
System.out.print(("\nThe car ") + CarObject.toString());
System.out.print(("\nThe truck ") + TruckObject.toString());
}
}
class Car extends Vehicle {
public String toString() {
String information;
information = super.toString() + " and " + noOfSeats + " seats";
return information;
}
}
class Truck extends Vehicle {
public String toString() {
String information;
information = super.toString() + " and has a towing capacity of " +
towingCapacity;
return information;
}
}
I have this code below: If I call my object statement like this I get this.
Output below:
trafficqueue.TrafficQueue$Car#1b26af3
trafficqueue.TrafficQueue$Car#8b819f
public class TrafficQueue {
private Car[] carArray;
private int numberOfcarsInQueue;
private int f = 0;
public TrafficQueue(int numberOfcarsInQueue){
carArray = new Car[numberOfcarsInQueue];
}
private static class Car {
private String make;
private String colour;
public Car(String make, String colour) {
this.make = make;
this.colour = colour;
}
public String getMake(){
return make;
}
} ;
public void add(Car car){
carArray[numberOfcarsInQueue] = car;
numberOfcarsInQueue ++;
}
public String toString()
{
String result = "";
for (int scan=0; scan < numberOfcarsInQueue; scan++)
result = result + carArray[scan].toString() + "\n";
return result;
}
public static void main(String[] args) {
// TODO code application logic here
TrafficQueue queueLane1 = new TrafficQueue(10);
Car carT = new Car("Toyota", "Red");
Car carE = new Car ("Jaguar","Red");
queueLane1.add(carT);
queueLane1.add(carE);
System.out.println(""+queueLane1.toString());
System.out.println(queueLane1);
System.out.println("Number of Cars in Queue"+ "=" + queueLane1.getNumberOfCarsInQueue());
}
}
I have tried using the java.util.arrays.toString but to no avail. What am I doing wrong?
The output that you're getting is produced by calling toString on the TrafficQueue object i.e. this method:
public String toString() {
String result = "";
for (int scan = 0; scan < numberOfcarsInQueue; scan++)
result = result + carArray[scan].toString() + "\n";
return result;
}
Let's examine the above method.
The above method calls carArray[scan].toString(). carArray[scan] is an instance of Car. What you're doing here is essentially calling toString on a Car.
Did you define a toString method for Car? Nope. That's why the default toString is called. That's why you see outputs like this
trafficqueue.TrafficQueue$Car#1b26af3
If you want a human readable string representation of Car, just override toString:
public String toString() {
return colour + " " + getMake();
}
Your whole Car class should look like this:
private static class Car {
private String make;
private String colour;
public Car(String make, String colour) {
this.make = make;
this.colour = colour;
}
public String getMake() {
return make;
}
#Override
public String toString() {
return colour + " " + getMake();
}
}
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());
I'm writing code for an application that keeps track of a student’s food purchases at a campus cafeteria. There's two classes - Student, which holds overloaded constructors & appropriate getter & setter methods; and MealCard, which holds a class variable to track the number of meal cards issued, appropriate getter & setter methods, a purchaseItem() method, a purchasePoints() method & an overriddden toString() method. There's a Tester class also.
In my MealCard class, the methods are written but in the Tester when I call them, they don't work correctly. I want to get the itemValue from the user but how do I do this in the MealCard class?
Same goes for the purchasePoints method, how do I get the topUpValue from user in MealCard class?
Code so far is:
public class Student {
// Instance Variables
private String name;
private int age;
private String address;
// Default Constructor
public Student() {
this("Not Given", 0, "Not Given");
}
// Parameterized constructor that takes in values
public Student(String name, int age, String address) {
this.name = name;
this.age = age;
this.address = address;
}
// Getters and Setters
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getAddress(){
return address;
}
public void setAddress(String address) {
this.address = address;
}
// toString() to be overriden
#Override
public String toString() {
return "Name: " + this.name + "\n" + "Age: " + this.age + "\n" + "Address: " + this.address;
}
}
`
public class MealCard extends Student {
static int numberOfMealCards;
private final static int DEFAULT_BALANCE = 1000;
private int itemValue;
private int topUpValue;
public int newBalance;
// Getters and Setters
public int getItemValue() {
return itemValue;
}
public void setItemValue(int itemValue) {
this.itemValue = itemValue;
}
public int getTopUpValue() {
return topUpValue;
}
public void setTopUpValue(int topUpValue) {
this.topUpValue = topUpValue;
}
// purchaseItem method for when students buy food
public int purchaseItem() {
newBalance = DEFAULT_BALANCE - itemValue;
return newBalance;
}
// purchasePoints method for students topping up their meal card balance
public int purchasePoints() {
newBalance = DEFAULT_BALANCE + topUpValue;
return newBalance;
}
// Overriden toString method
#Override
public String toString() {
return super.toString() + "Meal Card Balance: " + this.newBalance + "\n" + "Number of Meal Cards: " + numberOfMealCards;
}
}
`
import java.util.Scanner;
public class TestMealCard {
public static void main(String[] args) {
// Create instances of MealCard class
MealCard student1 = new MealCard();
MealCard student2 = new MealCard();
Scanner keyboard = new Scanner(System.in);
System.out.println("Name: ");
student1.setName(keyboard.nextLine());
System.out.println("Age: ");
student1.setAge(keyboard.nextInt());
System.out.println("Address: ");
student1.setAddress(keyboard.nextLine());
System.out.println("Meal Card Balace: ");
student1.newBalance = keyboard.nextInt();
System.out.println("Number of Meal Cards Issued: ");
student1.numberOfMealCards = keyboard.nextInt();
System.out.println("Name: ");
student2.setName(keyboard.nextLine());
System.out.println("Age: ");
student2.setAge(keyboard.nextInt());
System.out.println("Address: ");
student2.setAddress(keyboard.nextLine());
System.out.println("Meal Card Balace: ");
student2.newBalance = keyboard.nextInt();
System.out.println("Number of Meal Cards Issued: ");
student2.numberOfMealCards = keyboard.nextInt();
// Call purchaseItem
student1.purchaseItem();
// Call purchasePoints
student2.purchasePoints();
// Call tString to output information to user
}
}
In order to set the itemValue from the user you need to get get that input from the user using this setItemValue() method.
Ex.
System.out.print("Please enter the item value: ");
student1.setItemValue(keyboard.nextInt());
or
int itemVal = 0;
System.out.print("Please enter the item value: ");
itemVal = keyboard.nextInt();
student1.setItemValue(itemVal);
as for the other method call just call the setter for toUpValue.
Ex.
System.out.print("Please enter the item value: ");
student1.setTopUpValue(keyboard.nextInt());
or
int toUpVal = 0;
System.out.print("Please enter the item value: ");
itemVal = keyboard.nextInt();
student1.setTopUpValue(topUpVal);
Hope that helps =).