Object Oriented Programming, Method Call Not Working as Expected, Subclasses - java

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

Related

Adding object to an array list in Java

I am trying to add an object to an array list and have the following -
public static void main(String[] args) {
authors Authors = new authors();
ArrayList<authors> tabAuthors = new ArrayList<authors>();
Authors.setAuthId(1);
Authors.setAuthName("Roald Dahl");
System.out.println(Authors.toString());
tabAuthors.add(Authors);
Authors.setAuthId(2);
Authors.setAuthName("Julia Donaldson");
System.out.println(Authors.toString());
tabAuthors.add(Authors);
for (int counter =0; counter < tabAuthors.size(); counter++) {
System.out.println(tabAuthors.get(counter).getAuthId() + " " + tabAuthors.get(counter).getAuthName() );
}
}
}
The authors class
public class authors {
private int authId;
private String authName;
public int getAuthId() {
return authId;
}
public void setAuthId(int authId) {
this.authId = authId;
}
public String getAuthName() {
return authName;
}
public void setAuthName(String authName) {
this.authName = authName;
}
#Override
public String toString() {
return "authors{" +
"authId=" + authId +
", authName='" + authName + '\'' +
'}';
}
}
I was expecting the code to return -
1 Roald Dahl
2 Julia Donaldson
Instead, I am getting -
2 Julia Donaldson
2 Julia Donaldson
Why is the array list not reflecting the first object values ?
Because you create only one object and override second time when you set properties.
You need to create new object when you insert second object.
You are setting the value Julia Donaldson on the same Object. reference the variable Authors to a new object and the problem is solved.
authors Authors = new authors();
ArrayList<authors> tabAuthors = new ArrayList<authors>();
Authors.setAuthId(1);
Authors.setAuthName("Roald Dahl");
System.out.println(Authors.toString());
tabAuthors.add(Authors);
Authors = new Authors(); //Reference Authors to a new object here, or else
//you're using the same object and you'll overwrite the value Roald Dahl with
//Julia Donaldson
Authors.setAuthId(2);
Authors.setAuthName("Julia Donaldson");
System.out.println(Authors.toString());
tabAuthors.add(Authors);
In addition to the answer above by #Maurice, you can also add a constructor in authors class to set values for every object.
public authors(int authId, String authName) {
super();
this.authId = authId;
this.authName = authName;
}
In your main(), create two objects as below and add them to the list:
public static void main(String[] args) {
Authors authors1 = new Authors(1, "Roald Dahl");
Authors authors2 = new Authors(2, "Julia Donaldson");
List<Authors> tabAuthors = new ArrayList<Authors>();
System.out.println(authors1.toString());
tabAuthors.add(authors1);
System.out.println(authors2.toString());
tabAuthors.add(authors2);
for (int counter = 0; counter < tabAuthors.size(); counter++) {
System.out.println(tabAuthors.get(counter).getAuthId() + " " + tabAuthors.get(counter).getAuthName());
}
}
Output:
authors{authId=1, authName='Roald Dahl'}
authors{authId=2, authName='Julia Donaldson'}
1 Roald Dahl
2 Julia Donaldson
Thanks for your prompt responses.
I added the below in the code as I need to add indeterminate number of objects -
tabAuthors.add(new authors(authId,authName,authCountry,numBooks));
and declared authId,authName,authCountry,numBooks as variables.
The object values are being fetched from a database table.

Why the output is different, java inheritance?

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.

Comparing two objects through a boolean method, within my car class

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

Printing a particular String according to boolean value in Java

I m defining a Shape class with constructors, get and set methods, toString methods etc... And in toString method, I have to print " is Filled " or " is not Filled " according to a given boolean value.
I also wrote a getter method for boolean type such as:
...
...
private boolean filled;
...
...
//Constructor
public Shape(boolean f){
filled = f;
}
...
// Getter Method for Boolean values
public boolean isFilled(){
return filled;
}
But I have no idea how to write a proper toString method which prints out "is filled " or " is not filled " according to a given value of " boolean filled "
any help?
thanks in advance
You can use the ternary operator to achieve what you want
Solution
boolean filled;
// code
#Override
public String toString(){
return "blabla " + (filled? "filled" : "not filled") + " other blabla";
}
You can do it like following:
public String toString()
{
if(isFilled())
{
return "is filled";
}
else
{
return "is not filled ";
}
}
How about :
public String toString() {
return filled ? "is filled" : "is not filled";
}

Calling functions from different classes

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);
}

Categories

Resources