So I've created a three classes; PetStore, Pet, and Bird. The PetStore class is the main class, pet extends PetStore and then Bird extends off of Pet
And now I've created a driver class with the following code.
public class Main{
public static void main(String[] args){
//create a pet objects
Bird macaw = new Bird("hyacinth macaw", 300.99, 48.0);
//create a pet store
PetStore happyPetsInc = new PetStore();
//add the pets to the pet store
happyPetsInc.addPet(macaw);
I'm trying to add the bird object to the arraylist in PetStore.
I'm getting the error: "incompatible types: Bird cannont be converted to java.lang.String"
someone flagged this and said to post the PetStore and Bird Class so here that is:
public class PetStore
{
//varibles
String pet;
//ArrayList
ArrayList<String> Pets = new ArrayList<String>();
//constructor
public PetStore(){
}
/**
* add the paramameter to the ArrayList
* #param pet
* #return void
*/
public void addPet(String pet){
Pets.add(pet);
}
/**
* removes the paramater to the ArrayList
* #param pet
* #return true(success) false(failure)
*/
public boolean sellPet(String pet){
this.pet = pet;
if (Pets.contains(pet)){
Pets.remove(pet);
return true;
}else{
return false;
}
}
/**
* counts the number of elements in the ArrayList
* #param none
* #return int, the number of the elements in Pets
*/
public int getInventoryCount(){
return Pets.size();
}
/**
* displays information about the pets in the ArrayList
* #param none
* #return void
*/
public String toString(){
for (int i = 0; i < Pets.size(); i++){
System.out.println("Pet #" + (i + 1));
String index = Pets.get(i);
return index.toString();
}
return "\n";
}
}
public class Bird extends Pet
{
//varibale
double wingspan;
//constuctor
public Bird(String species, double cost, double wingspan){
super(species, cost);
this.wingspan = wingspan;
}
/**
* Sets the wingspan of the bird
* #param wingspan
* #return none
*/
public void setWingspan(double wingspan){
this.wingspan = wingspan;
}
/**
* Gets the wingspan of the bird
* #param none
* #return double
*/
public double getWingspan(){
return this.wingspan;
}
/**
* Displays strings describing the bird
* #param none
* #return String
*/
public String toString(){
return "Species: " + species + "\nCost: $" + cost + "\nBird (Wingspan: " + wingspan + " inches)";
}
}
The idea of object oriented programming is, to have classes and instances of classes (objects) to represent real life objects. Hence, a PetStore is about pets, not strings. So do this:
In PetStore replace
ArrayList<String> Pets ...
addPet(String pet)...
sellPet(String pet)...
with
ArrayList<Pet> Pets
addPet(Pet pet)
sellPet(Pet pet)
Also, in PetStore.toString() replace
String index = Pets.get(i);
With
Pet index = Pets.get(i);
you should define a Pet class, then in PetStore change
String pet;
to
Pet pet;
and also
ArrayList<String> Pets = new ArrayList<String>();
to
ArrayList<Pet> Pets = new ArrayList<Pet>();
Related
public abstract class Instrument {
private String id;
protected String maker;
private static int count = 0;
public Instrument(String maker)
{
count++;
id = "S" + count;
this.maker = maker;
}
public String getMaker()
{
return maker;
}
public String toString()
{
return "ID: " + id + ", Maker: " + maker;
}
abstract public void play(String music);
}
public class Piano extends Instrument
{
// instance variables - replace the example below with your own
private int year;
/**
* Constructor for objects of class Piano
*/
public Piano(int year, String maker)
{
// initialise instance variables
super(maker);
this.year = year;
}
/**
* An example of a method - replace this comment with your own
*
* #param y a sample parameter for a method
* #return the sum of x and y
*/
public int getyear()
{
// put your code here
return year;
}
public String toString()
{
return super.toString() + " Year: " + year;
}
public void play(String music)
{
System.out.println("Playing piano: " + music);
}
}
so basically I need to create class MusicShop that stores the Instrument objects in an ArrayList named
instruments. And then define a method to print out the details of all pianos made by a given
maker before a given year.
This is what ive done so far
public class MusicShop
{
// instance variables - replace the example below with your own
private ArrayList<Instrument> Instruments;
/**
* Constructor for objects of class MusicShop
*/
public MusicShop()
{
Instruments = new ArrayList<Instrument>();
}
public int getTotal()
{
return Instruments.size();
}
/**
* An example of a method - replace this comment with your own
*
* #param y a sample parameter for a method
* #return the sum of x and y
*/
public void printDetailsOfPiano()
{
// put your code here
for(Instrument aInstrument : Instruments) {
System.out.println(Instruments.getTotal);
}
}
}
Not sure how to store objects from abstract class into arraylist and print it details.
An object of type Piano can be added to the instruments without problems:
Piano piano = new Piano(1940, "Belarus");
List<Instrument> Instruments = new ArrayList<>();
Instruments.add(piano);
To print the details of an instrument, you need to do something similar to what you have done for play, you need a method print in Instrument.
Piano will override it.
For example:
public abstract class Instrument {
...
abstract public void print();
}
public class Piano extends Instrument {
...
#Override
public void print() {
System.out.println(getMaker() + " " + getYear() );
}
}
When you want to print the instruments, one way could be:
public void printDetailsOfPiano() {
Instruments.forEach( Instrument::print );
}
By the way, in Java the convention is to have the name of the variable not capitalized:
List<Instrument> instruments = new ArrayList<>();
I'm pretty new to Java but I feel like this is an easy task. This arraylist has two elements...names and scores. I want to write a method that prints a list of all the names in the list, not the scores. I know I've done this before I just can't remember how lol
import java.util.ArrayList;
/**
* Print test scrose and student names as well as he average for the class.
*/
public class TestScores {
private ArrayList<Classroom> scores;
public int studentScores;
/**
* Create a new ArrayList of scores and add some scores
*/
public TestScores() {
scores = new ArrayList<Classroom>();
}
/**
* Add a new student and a new score.
*/
public void add (String name, int score) {
scores.add(new Classroom(name, score));
if(score > 100){
System.out.println("The score cannot be more than 100");
}
}
/**
* Return all the student names.
*/
public void printAllNames() {//this is the method.
for (Classroom s : scores){
System.out.println(scores.get(name));
}
}
}
and the classroom class:
import java.util.ArrayList;
/**
* This class creates the names and scores of the students
*/
public class Classroom {
public int score;
public String name;
/**
* Constructor for the Class that adds a name and a score.
*/
public Classroom(String aName, int aScore) {
score = aScore;
name = aName;
}
/**
* Return the name of the students
*/
public String returnName() {
return name;
}
/**
* Return he scores
*/
public int returnScore() {
return score;
}
}
public void printAllNames() {//this is the method.
for (Classroom s : scores){
System.out.println(s.returnName());
}
}
You should be precice in your question, your list does not contain 2 elements - names and scores - but multiple Classroom objects which contain names and scores.
Alternative answer using Java 8 streams:
scores.stream().map(c -> c.returnName()).forEach(System.out::println);
Here is my problem I can't seem to figure out how to invoke a ParkingTicket object if (carMinutesPaid>meterMinutesPaid)? can any one help here are the details below to the question.
public static ParkingTicket checkParking(int carMinutesParked, int meterMinutesPaid)
{
Car parker = carMinutesParked;
ParkingMeter parkee = parkee;
if(carMinutesParked>meterMinutesPaid){
return new ParkingTicket(parker, parkee);
}
else if(carMinutesParked<=meterMinutesPaid){
System.out.println("null");
}
return new ParkingTicket(parker, parkee);
}
Here is the question for my project.
Remember, this method must be able to be used without a ParkingTicket object in existence.
Using a Car parameter and a ParkingMeter parameter, decide whether a ParkingTicket object should be created.
Invoke ParkingTicket(parker, parkee) if a ticket was merited, and return the result.
Return null if a ticket was not merited.
Here is my car class:
/**
* This is a Car class for Impark.
*
* #author Tre
* #version 2.0 15 October 2015
*/
public class Car
{
private static final int MINIMUM_PLATE_LENGTH=2;
private static final int MAXIMUM_PLATE_LENGTH=7;
public static final char MANUAL_TRANSMISSION='m';
public static final char AUTOMATIC_TRANSMISSION='a';
private static int defaultMinutesParked = 0;
private static double defaultOdometerInKm = 50000.5;
private String licensePlate;
private char transmissionType;
private double odometerInKm;
private int minutesParked;
/**
* #param newProposedLicensePlate the license plate of the car can equal null
* but must be between MINIMUM_PLATE_LENGTH and MAXIMUM_PLATE_LENGTH
*/
public Car(String newProposedLicensePlate)
{
setLicensePlate(newProposedLicensePlate);
transmissionType = AUTOMATIC_TRANSMISSION;
odometerInKm = defaultOdometerInKm;
minutesParked = defaultMinutesParked;
}
/**
* #return the license plate of the car can equal null
* but must be between MINIMUM_PLATE_LENGTH and MAXIMUM_PLATE_LENGTH
*/
public String getLicensePlate()
{
return licensePlate;
}
/**
* #return the transmission type MANUAL_TRANSMISSION or AUTOMATIC_TRANSMISSION
*/
public char getTransmissionType()
{
return transmissionType;
}
/**
* #return the odometer in kilometers
*/
public double getOdometerInKm()
{
return odometerInKm;
}
/**
* Recieve the license plate
* Mutator.licensePlate.
* #param proposedLicense String Conforming to ICBC *length* guidlines:
* http://www.icbc.com/vehicle-registration/license-plates/Pages/Personalized-licence-plates.aspx
* May also be null. The null represents a car without a plate
* If validation fails, null will be set.
*/
public void setLicensePlate(String proposedLicense)
{
if(proposedLicense==null){
licensePlate = proposedLicense;
}
else if(proposedLicense.length()>=MINIMUM_PLATE_LENGTH && proposedLicense.length()<=MAXIMUM_PLATE_LENGTH){
licensePlate = proposedLicense;
}
else{
licensePlate = null;
}
}
/**
* #param mOrA recieve the transmission type MANUAL_TRANSMISSION or AUTOMATIC_TRANSMISSION
* if invalid type of transmission is entered then will return "Installation failure: 'mOrA' is not a vaild transmission type"
*/
public void setTransmissionType(char mOrA)
{
if(mOrA==MANUAL_TRANSMISSION){
transmissionType = mOrA;
}
else if(mOrA==AUTOMATIC_TRANSMISSION){
transmissionType = mOrA;
}
else if (mOrA==mOrA){
System.out.println("Installation failure:" + " " + ("'")+(mOrA)+("'") + " " + "is not a valid transmission type.");
}
else{
transmissionType = mOrA;
}
}
/**
* #return the value of the odometer in with the String kilometers
*/
public String readOdometer()
{
return odometerInKm + " " + "kilometers";
}
/**
* #return the false if the minutesParked equals zero; otherwise true
*/
public boolean isParked()
{
if(minutesParked==defaultMinutesParked){
return false;
}
else{
return true;
}
}
/**
* #param duration replaces any existing value in minutesParked with the value from duration
*/
public void park(int duration)
{
if(duration>=defaultMinutesParked){
minutesParked = duration;
}
}
/**
* #param aOdometerInKm recieve the odometer in kilometers
*/
public void setOdometerInKm(double aOdometerInKm)
{
odometerInKm = aOdometerInKm;
}
/**
* #param aMinutesParked recieve the minutes parked in the stall but can not be a negative number
* if invalid number of minutes is entered then the number of minutes will not change.
*/
public void setMinutesParked(int aMinutesParked)
{
if(aMinutesParked>=defaultMinutesParked){
minutesParked = aMinutesParked;
}
else{
return;
}
}
/**
* #return the minutes parked
*/
public int getMinutesParked()
{
return minutesParked;
}
}
here is my ParkingMeter class:
/**
* This is a ParkingMeter class for Impark.
*
* #author Tre
* #version 2.0 15 October 2015
*/
public class ParkingMeter
{
private int minutesPaid;
private String methodPaid;
/**
* #param newMinutesPaid the minutes paid for parking meter
*/
public ParkingMeter()
{
}
/**
* #return the minutes paid
*/
public int getMinutesPaid()
{
return minutesPaid;
}
/**
* #return the method paid
*/
public String getMethodPaid()
{
return methodPaid;
}
/**
* #param paidBy the payment method customer will paid by
*/
public void setMethodPaid(String paidBy) /* BONUS for creating method paid */
{
if(methodPaid=="Visa"){
methodPaid = paidBy;
}
else if(methodPaid=="Master Card"){
methodPaid = paidBy;
}
else if(methodPaid=="American Express"){
methodPaid = paidBy;
}
else if(methodPaid=="Cash"){
methodPaid = paidBy;
}
else if(methodPaid=="Debit"){
methodPaid = paidBy;
}
else{
methodPaid = paidBy;
}
}
/**
* #param quantity the added minutes paid must not have a negative number
*/
public void addMinutesPaid(int quantity)
{
if(quantity>=0){
minutesPaid+=quantity;
}
}
}
and here is my ParkingTicket class:
/**
* This is a ParkingTicket class for Impark.
*
* #author Tre
* #version 1.0
*/
public class ParkingTicket
{
private final String referenceNumber;
private static String carLicensePlate;
private static int carMinutesParked;
private static int meterMinutesPaid;
private static int count = 1000;
private static String PREFIX = "V";
/**
* #param recorededLicense the value of the tick number
*/
private ParkingTicket(String recordedLicense, int newCarMinutesParked, int newMeterPaidMinutes)
{
referenceNumber = (PREFIX+count++);
carMinutesParked = newCarMinutesParked;
meterMinutesPaid = newMeterPaidMinutes;
}
/**
* #param
*/
private ParkingTicket(Car parker, ParkingMeter parkee)
{
this(parker.getLicensePlate(), parker.getMinutesParked(), parkee.getMinutesPaid());
}
/**
* #return referenceNumber the reference number
*/
public String getReferenceNumber()
{
return referenceNumber;
}
/**
* #return carLicensePlate the car's license plate
*/
public String getCarLicensePlate()
{
return carLicensePlate;
}
/**
* #return carMinutesParked the minutes car was parked
*/
public int getCarMinutesParked()
{
return carMinutesParked;
}
/**
* #return meterMinutesPaid the minutes paid on meter
*/
public int getMeterMinutesPaid()
{
return meterMinutesPaid;
}
/**
* #return count the with initial value of 1000
*/
public int getCount()
{
return count;
}
public static ParkingTicket checkParking(int carMinutesParked, int meterMinutesPaid)
{
Car parker = carMinutesParked;
ParkingMeter parkee = parkee;
if(carMinutesParked>meterMinutesPaid){
return new ParkingTicket(parker, parkee);
}
else if(carMinutesParked<=meterMinutesPaid){
return null;
}
return new ParkingTicket(parker, parkee);
}
}
This requirement:
Using a Car parameter and a ParkingMeter parameter, decide whether a
ParkingTicket object should be created.
suggests that you provide two parameters to the checkParking method, one is of the type Car and one of the ParkingMeter. So it should be like so:
public static ParkingTicket checkParking(Car car, ParkingMeter meter)
This code :
Car parker = carMinutesParked;
ParkingMeter parkee = parkee;
won't even compile
line 1: you're trying to assign int to object - that's called type mismatch.
line 2: variable parkee is not declared anywhere (except for the headline of the question).
You see, only the Car object holds the information about the parking duration, and you need the object for creating parking ticket. Same for the ParkingMeter
It should be vice versa - you get the values from the objects:
int carMinutesParked = car.getMinutesParked();
int meterMinutesPaid = meter.getMinutesPaid();
and proceed from here with if( or even use it in if without declaring temporary variables).
This one:
Invoke ParkingTicket(parker, parkee) if a ticket was merited, and
return the result.
you did OK.
Now this requirement:
Return null if a ticket was not merited.
suggest the method will return null, not string that equals to "null" .
So, based on these requirements it should rather be:
public static ParkingTicket checkParking(Car car, ParkingMeter meter)
{
//sanity check (bonus)
if ((car == null) || (meter == null))
return null;
if(car.getMinutesParked() > meter.getMinutesPaid()){
return new ParkingTicket(car, meter);
}
return null;
}
Note however, I don't know if you need any additional logic in this code and don't suggest this should be your final version, just explaining the general approach.
I have two classes. A class called Cat, that holds the cat names, birth year and weight in kilos. I have a class called Cattery that is an array. I want to input cats from the Cat class into the array. Each cat will have its own name, birth year and weight in Kilos. How do I do this? Thank you.
public class Cat {
private String name;
private int birthYear;
private double weightInKilos;
/**
* default constructor
*/
public Cat() {
}
/**
* #param name
* #param birthYear
* #param weightInKilos
*/
public Cat(String name, int birthYear, double weightInKilos){
this.name = name;
this.birthYear = birthYear;
this.weightInKilos = weightInKilo
}
/**
* #return the name.
*/
public String getName() {
return name;
}
/**
* #return the birthYear.
*/
public int getBirthYear() {
return birthYear;
}
/**
* #return the weightInKilos.
*/
public double getWeightInKilos() {
return weightInKilos;
}
/**
* #param the name variable.
*/
public void setName(String newName) {
name = newName;
}
/**
* #param the birthYear variable.
*/
public void setBirthYear(int newBirthYear) {
birthYear = newBirthYear;
}
/**
* #param the weightInKilos variable.
*/
public void setWeightInKilos(double newWeightInKilos) {
weightInKilos = newWeightInKilos;
}
}
The array class.
import java.util.ArrayList;
public class Cattery {
private ArrayList<Cat> cats;
private String businessName;
/**
* #param Cattery for the Cattery field.
*/
public Cattery() {
cats = new ArrayList<Cat>();
this.businessName = businessName;
}
/**
* Add a cat to the cattery.
* #param catName the cat to be added.
*/
public void addCat(Cat name)
{
Cat.add(getName());
}
/**
* #return the number of cats.
*/
public int getNumberOfCats()
{
return cats.size();
}
}
just edit the "addCat" method to pass object from argument to your ArrayList.
public void addCat(Cat name)
{
cats.add(name);
}
It seems that what you are trying to do is add cats to the cats list you declared in your Cattery. Another answer already notes the correction needed - your addCat method must be modified then to actually put the cats in the list. Note that you're not adding the cat name, but an actual Cat object. It also seems like you want the Cattery to have a business name. You can pass that in to the constructor.
public Cattery(String businessName) {
cats = new ArrayList<Cat>();
this.businessName = businessName;
}
...
public void addCat(Cat cat)
{
cats.add(cat);
}
Here's an example of how you may create your cattery and subsequently add cats. You must love cats.
class CatApp{
public static void main(String[] args) {
Cattery cattery = new Cattery("The Delicious Cats Business");
cattery.addCat(New Cat("Milo", 3, 388.87));
cattery.addCat(New Cat("Otis", 2, 1.4));
System.out.println("Total number of cats ready for consumption = "
+ cattery.getNumberOfCats());
}
}
I want to create several objects from a class in a for loop. but I don't know how to code it. What I have written creates a new object but it overwrites the previous object.
package assginment1_version4;
import java.util.*;
public class Client {
public static void main (String[] args) {
System.out.println ("this is a bill database");
System.out.println ("add a user?(Y/N)");
Scanner input = new Scanner(System.in);
String answer = input.nextLine ();
ArrayList ary = new ArrayList ();
for (int i=1 ; i < 100; i++) {
if (answer.equalsIgnoreCase("y")) {
Bill bill1 = new Bill();
System.out.println("user first name:");
bill1.setFname (input.nextLine());
System.out.println("user Last name:");
bill1.setLname (input.nextLine());
System.out.println ("add a user?(Y/N)");
answer = input.nextLine ();
} else if (answer.equalsIgnoreCase ("n")) {
if (Bill.getBillCounter () == 0) {
System.out.println ("the Database is empty");
break;
} else {
System.out.println ("Number of Users: "
+ Bill.getBillCounter ());
break;
}
} else {
while (!answer.equalsIgnoreCase ("n")
&& !answer.equalsIgnoreCase ("y")) {
System.out.println ("add a user?(Y/N)");
answer = input.nextLine ();
}
}
}
}
}
please help me to complete this code.
You're overriding them because you create a new Bill on each loop and never save them off anywhere. I believe you want to add them to your ArrayList:
First, you should add a type to your ArrayList:
ArrayList<Bill> ary = new ArrayList<Bill>();
Then, before you get the input from the user on whether or not to add a new Bill, you should add the current one to this list:
...
System.out.println("user Last name:");
bill1.setLname(input.nextLine());
ary.add(bill1);
...
You haven't used the ArrayList, you need to add the Bill's objects at the end of the for loop.
ary.add(bill1);
and add a type to your ArrayList
ArrayList<Bill> ary = new ArrayList<Bill>();
This is the Bill class.....
package assginment1_version2;
public class Bill {
/**
* Attributes of a bill
*/
private String firstName;
private String lastName;
private int paymentDeadline;
private int paymentCode;
private int billCode;
/**
* Attribute of Bill Class
*/
private static int BillCounter=0;
/**
* Methods of Bill class
* #return number of users
*/
/*public static int getBillCounter(){
return BillCounter;
}*/
/**
* Class Constructor
* #param Fname is the first name of user
* #param Lname is the last name of user
* #param Pdeadline is the deadline of paying the bill
* #param Pcode introduces the payment uniquely
* #param Bcode introduces the bill uniquely
*/
public Bill (){
BillCounter++;
}
/**
* FirstName methods
* method to set FirstName
* #param n is the input of setname method as a user name
*/
public void setFname (String n){
firstName=n;
}
// method to get FirstName
public String getFname (){
return firstName;
}
/**
* LastName methods
* method to set LastName
*/
public void setLname (String m){
lastName=m;
}
// method to get LastName
public String getLname(){
return lastName;
}
/**
* PaymentDeadline methods
* method to set PaymentDeadline
*/
public void setPaymentDeadline(int m){
paymentDeadline= m;
}
//method to get PaymentDeadline
public int getPaymentDeadline(){
return paymentDeadline;
}
/*
* PaymentCode methods
* Method to set PaymentCode
*/
public void setPaymentCode (int m){
paymentCode=m;
}
//method to get PaymentCode
public int getPaymentCode(){
return paymentCode;
}
/*
* Methods of BillCode
* method to set BillCode
*/
public void setBcode(int Bcode){
billCode=Bcode;
}
//method to get BillCode
public int getBcode(){
return billCode;
}
}