I am having trouble writing my main method within my car class. My class code is written as following;
public boolean compare (Car otherCar) {
return (model.equals(otherCar.model) && year == otherCar.year);
}
My problem is i am having trouble writing my main method i need to compare my "ferrari" car object with my "cobra" car object. I need to use an if/else statement and the method compare to compare the ferrari obj with the
cobra obj. And need to output "Same" if they are the same, or "Different" if they are different. All my other methods have been working fine besides this one.
Edit:
private String model;
private int year;
// default constructor
public Car()
{
model = "NA";
year = 0;
}
// overloaded constructor
public Car (String newModel, int newYear)
{
model = newModel;
year = newYear;
}
// mutator methods
public void setModel (String newModel)
{
model = newModel;
}
public void setYear (int newYear)
{
year = newYear;
}
// accessor methods
public String getModel()
{
return model;
}
public int getYear()
{
return year;
}
public boolean compare (Car otherCar)
{
return (model.equals(otherCar.model) && year == otherCar.year);
}
public void print()
{
System.out.println(model + " (" + year + ")");
}
}
My question is how should i write the if - else statement in my main method to compare these two objects using the compare method
Edit 2:` {
// Create an object of the class Car named ferrari
Car ferrari = new Car();
// Use the print method to print all information about the ferrari object.
ferrari.setModel("Ferrari");
ferrari.setYear(2010);
ferrari.print();
// Create an object of the class Car named cobra, passing parameters "Cobra" and 1967.
Car cobra = new Car("Cobra", 1967);
// Print information about the Cobra object using get methods.
System.out.println(cobra.getModel() + " " + cobra.getYear());
// Change the model of the cobra object to "Shelby Cobra".
cobra.setModel("Shelby Cobra");
// Change the year of the cobra object to 1963.
cobra.setYear(1963);
System.out.println(cobra.getModel() + " " + cobra.getYear());
// Use an if/else statement and the compare method to compare the ferrari obj with the
`
In your main method, you can simply write an if else for comparing cars and printing out like this,
if (ferrari.compare(cobra)) {
System.out.println("Both cars are same.");
} else {
System.out.println("Both cars are different.");
}
Another note, for printing objects values, you should better override toString() method that way you don't need to implement your print() method like you did. You can implement toString method like this,
public String toString() {
return String.format("model: %s, year: %s", model, year);
}
And then your if else can be written like this and will look better,
if (ferrari.compare(cobra)) {
System.out.println("("+ferrari + ") AND (" + cobra + ") cars are same");
} else {
System.out.println("("+ferrari + ") AND (" + cobra + ") cars are different");
}
Which will give following output,
(model: Ferrari, year: 2010) AND (model: Shelby Cobra, year: 1963) cars are different
Related
I'm finding it hard to use my methods even if I correctly instantiated my objects. Any ideas on where I went wrong?
example: I tried compiling the java file but the error I get is
"incompatible types: String cannot be converted to Books"
I think the problem is my instantiated object is being forced into a string but the problem is I used the correct syntax to call on a string. However, it still doesn't read it as a string and says that the instantiated object cannot be converted to the "Books" class.
I've already searched about it but all they say is the object hasn't been created. However, I checked my code and I already instantiated my object even before putting it into the method parameter.
I even tried to print the object on its own with the specific characteristics and it turned out fine. So I guess it goes right up until it gets put into a method.
One thing I don't understand is that I need that object to be referenced into a method.
Here is my code:
class Books{
String type;
int pages;
Books[] booklist;
int bookcounter = 0;
//Constructor to initialize the object "book"
Books(int input){
if(input == 1){
this.type = "Math";
this.pages = 5;
}
if(input == 2){
this.type = "Physics";
this.pages = 9;
}
if(input == 3){
this.type = "Economics";
this.pages = 20;
}
}
//This method needs to add the instantiated object to the array list
void addbooktype(Books kind){
System.out.println("You chose: " + kind);
System.out.println("Adding to the list...");
booklist[bookcounter++] = kind;
}
void printbooks(){
for(int i = 0; i <= bookcounter; i++){
int y = i+1;
System.out.println("Book #"+ y + "is: " +this.booklist[i].type);
System.out.println("With pages of: " + this.booklist[i].pages);
}
}
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int bookchoice;
int choice;
String booktype;
int booknum = 0;
do{
System.out.println("===========Menu===========");
System.out.println("[1] - Pick a book \n[2] - Print book list\n[0] - Exit");
System.out.println("==========================");
System.out.print("Choice: ");
choice = sc.nextInt();
switch(choice){
//Selects and adds a book to the list
case 1:
System.out.println("Choose your book: ");
bookchoice = sc.nextInt();
Books book = new Books(bookchoice);
System.out.println(book.type);
booktype = book.type;
book.addbooktype(booktype);
booknum++;
break;
//Prints the book list
case 2:
System.out.println("List of Books: ");
book.printbooks();
break;
case 0:
System.out.println("Exit");
return;
default: System.out.println("Input not found.");
}
}while(choice!=0);
}
}
The errors I get is on the "book.addbooktype(booktype);"
This is where it bugs me, I printed the objected and even put it into a String container but it still rejects it. I don't know where I went wrong. And when it goes into the method it doesn't read the parameter. Any thoughts?
Your method addbooktype requires a parameter of Books type whereas you wanted a String parameter there
void addbooktype(Books kind){
Your code would work if you would make this slight change:
void addbooktype(String kind){
Edit: As per the comments, it seems I misunderstood the code. That being said, here's what you can do:
Replace
book.addbooktype(booktype);
with
book.addbooktype();
and replace
void addbooktype(Books kind){
System.out.println("You chose: " + kind);
System.out.println("Adding to the list...");
booklist[bookcounter++] = kind;
}
with
void addbooktype(){
System.out.println("You chose: " + this.kind);
System.out.println("Adding to the list...");
booklist[bookcounter++] = this;
}
This would add the currently calling object to your array and allow you to use it later.
The issue is that your method accepts Object of Class Book only. However when you are calling that function
book.addbooktype(booktype);
You are giving it type String (In your book class type is String variable). To fix that you either need to pass book object or change the method itself
Passing the book object:
Books book = new Books(bookchoice);
book.addbooktype(book);
and in function you can do something like this
void addbooktype(Books book) {
System.out.println("You chose: " + book.type);
System.out.println("Adding to the list...");
booklist[bookcounter++] = book;
}
(Added Later) Using This:
This approach also utilizes the object however it is better than the approach described above. Instead of passing the object as a parameter which is redundant you can use java word this.
According to java docs Using the this Keyword
Within an instance method or a constructor, this is a reference to the current object — the object whose method or constructor is being called. You can refer to any member of the current object from within an instance method or a constructor by using this.
So when you call function
book.addbooktype(book);
^ and ^ are same
| |
Inside the method addbooktype
void addbooktype(Books book) {
this and book would also be same.
}
so instead you could do this
book.addbooktype();
and addbooktype would be
void addbooktype() {
System.out.println("You chose: " + this.type);
System.out.println("Adding to the list...");
booklist[bookcounter++] = this;
}
An example where passing object and this would be useful is when you have to compare objects. Lets say you have two objects book1 and book2. You would do something like this
int compareResult = book1.compareTo(book2);
Your method would be
public int compareTo(Book book) {
Now here this would be book1
and book would be book2
Also keep in mind this.type would be same as type. type and this.type are both
referring to same object i.e who we called function on (book1).
}
Changing the function:
or you can just change you function like this though I suggest you pass the object itself. If you just pass the String you won't be able to store it in Books[] booklist
void addbooktype(String type) {
System.out.println("You chose: " + type);
System.out.println("Adding to the list...");
// The line below will give error unless you change Books[] booklist;
// to String[] booklist;
booklist[bookcounter++] = kind;
}
I've got 2 classes, car extends vehicle, Why, when I'm trying to print a new created car object the output isn't equal as I thought.
I'm running it on Eclipse, java 11
public class vehicle_13 {
private int years;
public vehicle_13(int y) {
years=y;
}
public int years() {
return years;
}
public String driving() {
return "Can drive";
}
public int speed() {
return 50;
}
public String toString() {
return "years = "+years()+"\n"+this.driving()+"\n"+"speed = "+this.speed()
+"\n"+this.money_per(); // driving() = this.driving()
}
public int money_per() {
return years*10;
}
}
public class car_13 extends vehicle_13 {
public car_13(int y) {
super(0);
}
public int speed() {
System.out.println(super.driving());
return super.speed()*2;
}
}
I expect the output of this car object .toString() to be:
years = 0
Can drive
Can drive
speed = 100
0
but the actual output is:
Can drive
years = 0
Can drive
speed = 100
0
When you concatenate the string like this:
return "years = " + years() + "\n" + this.driving() + "\n"
+ "speed = " + this.speed() + "\n" + this.money_per();
It has to execute each of the methods before it creates the string. After all, it's the result of executing the method that gets added to the string. So the println in the speed method is called when this.speed() is evaluated, then the concatenated string is returned by toString, and then the result is passed to System.out.println. So the println in speed runs before the println in main, not in the middle of it.
P.S: Long concatenation like this, is better suited to the String.format method
return String.format("years = %d\n%d\nspeed = %d\n%d",
years(), driving(), speed(), money_per());
You have called super.driving in the sub-class and that is what is evaluated first. Therefore it prints out "Can drive" first, before the result of the toString as you expected.
I am having trouble with my call to the method makeNoise in the Pets class. I call the makeNoise method through another class, Humans, that has a makePetMakeNoise method:
public void makePetMakeNoise()
{
int randnum = (int)(Math.random() *5);
pet.makeNoise(randnum);
}
And I set the pets' canMakeNoise boolean when I create it: Cat a = new Cat("Critter", "Meow", true);
When I call the Humans' makePetMakeNoise method, I only get a printout like so: Critter remains silent instead of: Meow Critter. Why is this, and how do I fix it? Thanks.
public class Pets
{
String name;
String noise;
boolean canMakeNoise;
public Pets(String pname, String pnoise, boolean pcanmakenoise)
{
name = pname;
noise = pnoise;
pcanmakenoise = canMakeNoise;
}
public void makeNoise(int number)
{
if(canMakeNoise==true)
{
for(int i=0; i<number; i++)
{
System.out.println(noise + " " + name);
}
}
else if(canMakeNoise==false)
{
System.out.println(name + " *remains silent*");
}
}
public void eat()
{
System.out.println(name + " is eating...");
}
}
It looks like the assignment for "canMakeNoise" in the constructor is reversed, i.e. assign canmakenoise = pcanmakenoise.
Change this line from
pcanmakenoise = canMakeNoise;
to
canMakeNoise = pcanmakenoise;
You assigned the constructor parameter pcanmakenoise with the value of canMakeNoise which is currently null.
pcanmakenoise = canMakeNoise;
Default boolean value is false.
canMakeNoise is always false; Hence below condition is always called.
else if(canMakeNoise==false)
Reference ::
https://msdn.microsoft.com/en-us/library/83fhsxwc.aspx
https://www.google.com/search?q=c%23+default+boolean+value&ie=utf-8&oe=utf-8
I'm writing a program and I'm supposed to check and see if a certain object is in the list before I call it. I set up the contains() method which is supposed to use the equals() method of the Comparable interface I implemented on my Golfer class but it doesn't seem to call it (I put print statements in to check). I can't seem to figure out whats wrong with the code, the ArrayUnsortedList class I'm using to go through the list even uses the correct toString() method I defined in my Golfer class but for some reason it won't use the equals() method I implemented.
//From "GolfApp.java"
public class GolfApp{
ListInterface <Golfer>golfers = new ArraySortedList<Golfer> (20);
Golfer golfer;
//..*snip*..
if(this.golfers.contains(new Golfer(name,score)))
System.out.println("The list already contains this golfer");
else{
this.golfers.add(this.golfer = new Golfer(name,score));
System.out.println("This golfer is already on the list");
}
//From "ArrayUnsortedList.java"
protected void find(T target){
location = 0;
found = false;
while (location < numElements){
if (list[location].equals(target)) //Where I think the problem is
{
found = true;
return;
}
else
location++;
}
}
public boolean contains(T element){
find(element);
return found;
}
//From "Golfer.java"
public class Golfer implements Comparable<Golfer>{
//..irrelavant code sniped..//
public boolean equals(Golfer golfer)
{
String thisString = score + ":" + name;
String otherString = golfer.getScore() + ":" + golfer.getName() ;
System.out.println("Golfer.equals() has bee called");
return thisString.equalsIgnoreCase(otherString);
}
public String toString()
{
return (score + ":" + name);
}
My main problem seems to be getting the find function of the ArrayUnsortedList to call my equals function in the find() part of the List but I'm not exactly sure why, like I said when I have it printed out it works with the toString() method I implemented perfectly.
I'm almost positive the problem has to do with the find() function in the ArraySortedList not calling my equals() method. I tried using some other functions that relied on the find() method and got the same results.
Your equals method should take an Object argument, not a Golfer. The equals(Golfer) method is overloading the Comparable's equals(Object) method but does not implement it. It's simply an overloaded method no other code knows about, so it doesn't get called.
public boolean equals(Object obj)
{
if(!(obj instanceof Golfer)) return false;
Golfer golfer = (Golfer)obj;
String thisString = score + ":" + name;
String otherString = golfer.getScore() + ":" + golfer.getName() ;
System.out.println("Golfer.equals() has bee called");
return thisString.equalsIgnoreCase(otherString);
}
I am done with this assignment think god, and was wondering if someone could please check it so I can make sure there are no errors, it seems like I work hard on these programs but always doing something wrong. I am doing this course online so I have a hard time communicating with the instructor. I think my equals to methods might be wrong but, they seem to have no error when running the program and the program is 100% done. Please take the time to look over it, and thank you so much for your time.
Assignment:
About the first class
Create a class named RoomDimension that has two fields: one for the length of the room and another for the width. The RoomDimension class should have two constructors: one with no parameters (a default) and one with two parameters. The class should have all of the appropriate get and set methods, a method that returns the area of the room, a toString method that will allow us to print the length, width and area of the room and an equals method to compare room dimensions.
About the second class
Create another class named RoomCarpet that has two fields: one is a RoomDimension object and the other is a field that holds the cost of carpet per square foot. The class should have two constructors: one with no parameters and one with the two field parameters (RoomDimension and double). The class should have a get and set method for each field, a method that returns the total cost of carpeting the room, a toString method that will print all of the room information (length, width, area) and cost of the carpet per square foot and the total cost to carpet the room. (Dollar amounts should be displayed with two decimal places.), and an equals method that compares room dimensions and carpet cost.
About the application program
Write an application program that contains one RoomDimension object and one RoomCarpet object. The program should allow the user to enter the length and width of the room and the cost of the carpet per square foot. The program should instantiate both objects and use a simple System.out.println statement to print all of the information about the RoomCarpet object.
MY code:
import java.text.DecimalFormat;
public class RoomCarpet {
private RoomDimension rmSize;
private double pricePerSqFt;
//default constructor
public RoomCarpet()
{
this.rmSize = new RoomDimension();
this.pricePerSqFt = 0.00;
}
//parameters constructor
public RoomCarpet(RoomDimension rmSize, double pricePerSqFt)
{
this.rmSize = new RoomDimension(rmSize.getRmLength(),rmSize.getRmWidth());
this.pricePerSqFt = pricePerSqFt;
}
//accessor methods
public RoomDimension getRmSize()
{
return new RoomDimension(rmSize.getRmLength(),rmSize.getRmWidth());
}
public double getPricePerSqFt()
{
return this.pricePerSqFt;
}
// mutator methods
public void setRmSize(RoomDimension rmSize)
{
this.rmSize = new RoomDimension(rmSize.getRmLength(), rmSize.getRmWidth());
}
public void setPricePerSqFt(double pricePerSqFt)
{
this.pricePerSqFt = pricePerSqFt;
}
// Or price for the room to be carpeted
public double rmTotalCost()
{
return rmSize.getAreaRoom() * pricePerSqFt;
}
//toString method
public String toString()
{
DecimalFormat dollar = new DecimalFormat("$#,##0.00");
String str = this.rmSize.toString() + " Price per sq. ft : " +dollar.format(pricePerSqFt) + " Price to carpet Room: " + dollar.format(rmTotalCost()) + '\n';
return str;
}
public boolean equals(RoomCarpet object2)
{
boolean status;
if ((this.equals(object2)==true)&&(this.pricePerSqFt==object2.pricePerSqFt))
status = true;
else
status = false;
return status;
}
}
public class RoomDimension {
private int rmLength;
private int rmWidth;
//Default constructor
public RoomDimension()
{
rmLength=0;
rmLength=0;
}
// constructor with parameters
public RoomDimension(int rmLength, int rmWidth)
{
this.rmLength=rmLength;
this.rmWidth=rmWidth;
}
// accessor methods
public int getRmLength()
{
return this.rmLength;
}
public int getRmWidth()
{
return this.rmWidth;
}
//mutator methods
public void setRmLength(int rmLength)
{
this.rmLength=rmLength;
}
public void setRmWidth(int rmWidth)
{
this.rmWidth =rmWidth;
}
//area of the room
public int getAreaRoom()
{
return this.rmLength * this.rmWidth;
}
//toString Method
public String toString()
{
String str = "Room Length: " + this.rmLength + " Room Width: " + this.rmWidth + " Area of Room: " + this.getAreaRoom();
return str;
}
public boolean equals(RoomDimension object2)
{
boolean status;
if (this.getAreaRoom() == object2.getAreaRoom())
status = true;
else
status = false;
return status;
}
}
import java.util.Scanner;
public class CarpetPrice {
public static void main(String[] args)
{
RoomDimension rmSize;
RoomCarpet rmCarpet;
Scanner keyboard = new Scanner(System.in);
rmSize=new RoomDimension();
System.out.println(" Please enter the length of the room: ");
int rmLength= keyboard.nextInt();
rmSize.setRmLength(rmLength);
System.out.println("Please enter the rooms width: ");
int rmWidth = keyboard.nextInt();
rmSize.setRmWidth(rmWidth);
System.out.println("Please enter the price per sq foot: ");
double pricePerSqFt = keyboard.nextDouble();
rmCarpet = new RoomCarpet(rmSize, pricePerSqFt);
System.out.println("\n"+rmCarpet.toString());
}
}
The equals method must have an Object argument and you have to override the hashCode method too.
#Override
public boolean equals(Object obj)
{
}
I would say that for RoomDimension, two objects are equal only if both length and width match. Especially if you're laying carpet, a 4x5 room would be much different from a 1x20 hallway, even though the total area is the same. For the RoomCarpet object, again equal only if both the dimensions are equal and the price is the same, I guess.
Also, I would write some tests because you may be surprised at what happens when you call RoomCarpet's .equals() method (as written above).
Finally, pay attention to your indenting because that's important for any reader of your code.