Writing a main class to output from 2 other classes. There are 6 variables being passed but only the last 3 are printing correctly. The first 3 all return null. Here is the output:
DOG DATA
null is a null, a null dog.
The top trick is : Spinner.
The Corgi is 12 years old and weighs 20 pounds.
public class Dog {
// instance variables
public static String type;
public static String breed;
public static String name;
public static String topTrick;
// constructor
public Dog(String type, String breed, String name) {
type = "No type";
breed = "No breed";
name = "No name";
}
// methods
public static String setTopTrick(String trick) {
topTrick = trick;
return trick;
}
// method used to print Dog information
public String toString() {
String temp = "\nDOG DATA\n" + name + " is a " + breed +
", a " + type + " dog. \nThe top trick is : " +
topTrick + ".";
return temp;
}
}
ublic class Corgi extends Dog {
// additional instance variables
public static int weight;
public static int age;
// constructor
public Corgi(String type, String breed, String name, int pounds, int years) {
// invoke Dog class (super class) constructor
super(type, breed, name);
weight = pounds;
age = years;
}
// mutator methods
public static int setWeight(int pounds) {
weight = pounds;
return pounds;
}
public static int setAge(int years) {
age = years;
return years;
}
// override toString() method to include additional dog information
#Override
public String toString() {
return (super.toString() + "\nThe Corgi is " + age +
" years old and weighs " + weight + " pounds.");
}
}
public class Driver {
public static void main(String[] args) {
Corgi sleeper = new Corgi("Geriatric", "Pembroke Welsh", "Ein", 20, 12);
sleeper.setTopTrick("Spinner");
System.out.println(sleeper);
}
}
Literally everything in your program except main that is static should not be static. Static variables are not instance variables.
Also, your Dog constructor is incorrect, and should be
this.type = type;
this.breed = breed;
this.name = name;
Related
I am new to java, and I am trying to create a method to update the instance variable age for my objects. I am getting the code to compile, but I am seeing no change in the age value. This code is part of an assignment, so I cannot change the constructors. The method I wrote to update the age (that doesn't work) is shown below. My entire code is shown below that. I am also curious if there's a way to update/change just one of my objects, but before I do that, I need the method to work for both. Any help writing this method properly would be appreciated!
public void setnewAge(int age) {
dogAge += 1;
this.dogAge = dogAge;
}
Below is my entire code (including the method I wrote to update age).
public class Dog {
//Instance Varibles
private String dogName;
private int dogAge;
private int dogWeight;
//Two Contructors (One Completely Empty)
public Dog() {
}
public Dog(String name, int age, int weight){
dogName = name;
dogAge = age;
dogWeight = weight;
}
//Getters
public String getName() { return dogName;}
public int getAge() { return dogAge;}
public int getWeight() { return dogWeight;}
//Setters
public void setName(String theName) { dogName = theName;}
public void setAge(int theAge) {dogAge = theAge;}
public void setWeight(int theWeight) {dogWeight = theWeight;}
//to(String) method
public String toString() {
return "The dogs's name is " + getName() + ", the dogs's age is " +
getAge() + ", " + "\n" + "the dogs's weight is " + getWeight() + ".";
}
public void setnewAge(int age) {
dogAge += 1;
this.dogAge = dogAge;
}
//Main Method
public static void main(String[] args) {
Dog poodle = new Dog("Bob", 5, 26);
System.out.println(poodle);
Dog lab = new Dog();
lab.setName("Steve");
lab.setAge(8);
lab.setWeight(43);
System.out.println(lab);
}
}
As Tom said, you need to actually call the function in your main function otherwise, there will be no change, and also to refine your code for your setnewAge function, try this:
public void setnewAge() {
this.dogAge = dogAge + 1;
}
Then in the main function call setnewAge() and then print your age to see the results.
Dog poodle = new Dog("Bob", 5, 26);
poodle.setnewAge() ;
What an amazing platform! I hope im not asking a too stupid question but i have searched for an answer without success.
Q:
Is it possible to compare object values created by a constructor? Like if i want to make the animals fight and compare the "str" values against eachother.
My goal is to create the "fight" method in the Animal class, not in main. In that way, i can just call it like "dog.fight();
See my code for an example (sorry for my english)
public class Animal {
private int str;
private int agi;
private String name;
private String eyeColour;
public void set (int strenght, int agility, String _name){
str = strenght;
agi = agility;
name = _name;
}
public String get (){
System.out.println("Created a new animal named " + name +"! ");
System.out.println(name + "'s agility is " + agi);
System.out.println(name + "'s strenght is " + str);
return name + str + agi;
}
}
import java.util.Scanner;
public class Hello {
public static void main(String[] args) {
Animal dog = new Animal ();
dog.set(8, 4, "Rambo");
dog.get();
System.out.println("");
Animal cat = new Animal ();
cat.set(2, 9, "Felix");
cat.get();
}
}
You need to create a method 'fight' in the Animal class the takes as parameter an Animal object and use it to return to you the result of the winner.
Here is the code :
public class Animal {
private int str;
private int agi;
private String name;
private String eyeColour;
public void set (int strenght, int agility, String _name){
str = strenght;
agi = agility;
name = _name;
}
public String get (){
System.out.println("Created a new animal named " + name +"! ");
System.out.println(name + "'s agility is " + agi);
System.out.println(name + "'s strenght is " + str);
return name + str + agi;
}
public String fight(Animal rival){
//Provide Comparison Logic Here
if(this.str>rival.str)return this.name;
if(this.str < rival.str)return rival.name;
return "No One ";
}
}
public class Hello {
public static void main(String[] args) {
Animal dog = new Animal ();
dog.set(8, 4, "Rambo");
dog.get();
System.out.println("");
Animal cat = new Animal ();
cat.set(2, 9, "Felix");
cat.get();
System.out.println(dog.fight(cat)+" is the winner! ");
}
}
A Small side notes here:
It would be much better to use constructors instead of set Method here, as normally setter and getter are created to set or get a single variable.
Also it's better to change the name of your get Method and override toString method.
Here's the modified code:
public class Animal {
private int str;
private int agi;
private String name;
private String eyeColour;
public Animal (int str, int agi, String name){
this.str = str;
this.agi = agi;
this.name = name;
}
#Override
public String toString(){
String description = "Created a new animal named " + name +"!\n";
description+=name + "'s agility is " + agi+"\n";
description+=name + "'s strenght is " + str;
return description;
}
public String fight(Animal rival){
//Provide Comparison Logic Here
if(this.str>rival.str)return this.name;
if(this.str < rival.str)return rival.name;
return "No One ";
}
}
public class Hello {
public static void main(String[] args) {
Animal dog = new Animal (8, 4, "Rambo");
System.out.println(dog);
System.out.println();
Animal cat = new Animal (2, 9, "Felix");
System.out.println(cat);
System.out.println(dog.fight(cat)+" is the winner! ");
}
}
I have written a simple program that has an Animal super type and a Dog and Cat subtypes. The subtypes inherit 3 instance variables, name, weightInKg, and animalId. Each subtype has its own unique boolean, barks and swims.
I have a Farm class that adds Animal object to an ArrayList and a method that displays the toString() methods of each object in the collection. I want to create a pre-fix code to be displayed instead of each objects unique animalId in the toString() method. For example, if it is a Dog subtype "d1" will be displayed for all Dog objects.
Is there a way to do this?
I know that the obvious answer would be to put the code in as the animalId but thats not what I am trying to accomplish. Thanks!`
Animal:
public class Animal {
private String name;
private double weightInKg;
private String animalId;
public Animal() {}
public Animal(String name, double weightInKg, String animalId) {
setName(name);
setWeightInKg(weightInKg);
setAnimalId(animalId);
}
//getters and setter ommitted
public String getAnimalId() {
return animalId;
}
public void setAnimalId(String animalId) {
this.animalId = animalId;
}
#Override
public String toString() {
return "Animal [name=" + name + ", weightInKg=" + weightInKg + ", animalId=" + animalId + "]";
}
}
Dog:
public class Dog extends Animal {
private boolean barks;
public Dog() {}
public Dog(String name, double weightInKg, String animalId, boolean barks) {
super(name, weightInKg, animalId);
setBarks(barks);
}
public boolean isBarks() {
return barks;
}
public void setBarks(boolean barks) {
this.barks = barks;
}
#Override
public String toString() {
return "Dog [barks=" + barks + ", toString()=" + super.toString() + "]";
}
}
Cat:
public class Cat extends Animal {
private boolean swims;
public Cat() {}
public Cat(String name, double weightInKg, String animalId, boolean swims) {
super(name, weightInKg, animalId);
setSwims(swims);
}
public boolean isSwims() {
return swims;
}
public void setSwims(boolean swims) {
this.swims = swims;
}
#Override
public String toString() {
return "Cat [swims=" + swims + ", toString()=" + super.toString() + "]";
}
}
Farm:
import java.util.ArrayList;
public class Farm {
private ArrayList < Animal > farm;
public Farm() {
farm = new ArrayList < Animal > ();
}
public void addToFarm(Animal newAnimal) {
farm.add(newAnimal);
}
public void displayAllAnimals() {
int counter = 0;
while (farm.size() > counter) {
System.out.println(farm.get(counter));
}
}
}
I'm not 100% clear on what you what the output to look like, perhaps an example would help.
However you could convert the Animal class to be abstract and add an abstract "prefix" method which all the subclasses would have to implement. For example:
public abstract class Animal {
...
protected abstract String prefix();
#Override
public String toString() {
return "Animal [prefix=" + prefix() + ", name=" + name + ", weightInKg=" + weightInKg + ", animalId=" + animalId + "]";
}
}
See https://docs.oracle.com/javase/tutorial/java/IandI/abstract.html
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
Directions: http://imgur.com/kw6A0JX
I don't think I am printing out the objects correctly. My teacher helped me with the first part so I believe I am assigning them correctly. When printing them out, do I use "this" command? What is the right syntax for this type of situation?
Thank you.
public static void main(String [ ] args) {
Dog1 Rover = new Dog1("Rover", 4);
Sheep1 Wooly = new Sheep1("Wooly", 4);
Duck1 Daffy = new Duck1("Daffy", 2);
Cat1 Ketty = new Cat1("Ketty", 4);
System.out.println(name.Dog1, getHello.Dog1, isCarnivorous.Dog1, isMammal.Dog1);
System.out.println(name.Sheep1, getHello.Sheep1, isCarnivorous.Sheep1, isMammal.Sheep1);
System.out.println(name.Duck1, getHello.Duck1, isCarnivorous.Duck1, isMammal.Duck1);
System.out.println(name.Cat11, getHello.Cat1, isCarnivorous.Cat1, isMammal.Cat1);
}
Updated:
public abstract class Animal1 { //creating Animal1 which is the base and parent class, it is abstract so abstract classes can be created below
private String animalName; //defining animalName as private
public int numberOfLegs; //# of legs as public
public Animal1(final String name){ //first constructor with only assigning name
animalName = name;
}
public Animal1(final String name, final int legs){ //second constructor assigning both name and number of legs
animalName = name;
numberOfLegs = legs;
}
public String getName(){ //first getMethod for animalName
return animalName;
}
public int getLegs(){ //second getMethod for returning numberOfLegs
return numberOfLegs;
}
public boolean isMammal(){ //returning true value with boolean
return true;
}
public boolean isCarnivorous(){ //returning true value with boolean
return true;
}
public abstract String getHello(); //creating an abstract method, possible because base class is also abstract
}
public class Cat1 extends Animal1{ //child class of Animal1
public Cat1(final String name){ //Creating class constructor taking a name, within the constructor call the parent class constructor taking one argument
super(name, 4);
}
#Override
public String getHello(){ //Overriding getHello to return "Meow"
return "Meow";
}
}
public class Dog1 extends Animal1{ //another child of Dog1
public Dog1(final String name){ //Creating class constructor taking a name, within the constructor call the parent class constructor taking one argument
super(name, 4);
}
#Override
public String getHello(){ //Overriding getHello to return "Woof"
return "Woof";
}
}
public class Duck1 extends Animal1{ //third child class of Animal1
public Duck1(final String name){ //Creating class constructor taking a name, within the constructor call the parent class constructor taking one argument
super(name, 2);
}
#Override
public boolean isMammal(){ //Overriding isMammal() function to return false, as a duck is not a mammal
return false;
}
#Override
public boolean isCarnivorous(){ //Overriding isCarnivorous() function to return false as a duck is not a carnivore
return false;
}
#Override
public String getHello(){ //Overriding getHello to return "Quack"
return "Quack";
}
}
public class Sheep1 extends Animal1{ //fourth child class of Animal1
public Duck1(final String name){ //Creating class constructor taking a name, within the constructor call the parent class constructor taking one argument
super(name, 2);
}
#Override
public boolean isCarnivorous(){ //Overriding isCarnivorous() function to return false as a sheep is not a carnivore
return false;
}
#Override
public String getHello(){ //Overriding getHello to return "Baa"
return "Baa";
}
}
public static void main(String [ ] args) {
Dog1 Rover = new Dog1("Rover", 4);
Sheep1 Wooly = new Sheep1("Wooly", 4);
Duck1 Daffy = new Duck1("Daffy", 2);
Cat1 Ketty = new Cat1("Ketty", 4);
System.out.println(Rover.getName() + ", " + Rover.getHello() + ", " + Rover.isCarnivorous() + ", " + Rover.isMammal());
System.out.println(Wooly.getName() + ", " + Wooly.getHello() + ", " + Wooly.isCarnivorous() + ", " + Wooly.isMammal());
System.out.println(Daffy.getName() + ", " + Daffy.getHello() + ", " + Daffy.isCarnivorous() + ", " + Daffy.isMammal());
System.out.println(Ketty.getName() + ", " + Ketty.getHello() + ", " + Ketty.isCarnivorous() + ", " + Ketty.isMammal());
}
Your syntax is wrong. You need to refer to the variable by name, not by class. And the method comes after the object. And System.out.println() doesn't accept multiple arguments. Try this:
System.out.println(Rover.getName() + ", " + Rover.getHello() + ", " + Rover.isCarnivorous() + ", " + Rover.isMammal());
Similarly for the other lines.
You've got your syntax reversed. If these are all methods that you're calling, then they're done like Dog1.name(). If they're just public variables, you can call them like Dog1.name.
Also, a word of advice - most object instants in java follow the syntax of first word lowercase, following words uppercase (like your methods). Not crucial, but helpful to know.
Edit: Yep, it's just what the first line of this answer reads. To get the boolean from your animal class, just call them with first the object's name, then .exampleMethod().
Also, for your print statements, the println method might print the statements funny if you leave it as it is. What you can do instead is just add some strings in between like so:
System.out.println("Name: " + Dog1.getName() + ", Hello: " + Dog1.getHello()...); // rest of line excluded for brevity
The keyword this refers to the current object.
public class Test
{
public static void main(String[] args)
{
Dog1 dog = new Dog1("Rover", 4);
System.out.println(dog.name() + " " + dog.hello() + " " + dog.carnivorus() + " " + dog.mammal() + ".");
}
}
class Dog1
{
private String name;
private int age;
private String hello;
private boolean carnivorus;
private boolean mammal;
public Dog1(String name, int age)
{
this.name = name;
this.age = age;
this.hello = "woof woof";
this.carnivorus = true;
this.mammal = true;
}
public String name()
{
return this.name;
}
public String hello()
{
return this.hello;
}
public boolean carnivorus()
{
return this.carnivorus;
}
public boolean mammal()
{
return this.mammal;
}
}
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
I'm supposed to make a program that has MotorVehicle abstract class. Car, Truck, Van are kinds of MotorVehicle. The setTerms() and displayInfo() are the only abstract. Car has String transType and void Car(), Van has int numPassenger and void Van(), as Truck has double payLoad and void Truck().
The output should be like this:
Brand is Mazda
Vehicle type is Sedan
Color is Red
Transmission type is Automatic
Price is 840000.0
Terms is 5 years to pay
Brand is Isuzu
Vehicle type is Truck
Color is White
Payload capacity is 3.5
Price is 910000.0
Terms is 3 years to pay
Brand is Mitsubishi
Vehicle type is Family Van
Color is Blue
Number of passenger is 8
Price is 1050000.0
Terms is 7 years to pay
But my program doesn't still produce this output
Here's my current codes:
public abstract class MotorVehicle
{
private String vehicleType;
private String brand;
private String color;
private String terms;
public MotorVehicle(String vcl, String brn, String clr, String trm)
{
vehicleType = vcl;
brand = brn;
color = clr;
terms = trm;
}
public String getVehicleType()
{
return vehicleType;
}
public String getBrand()
{
return brand;
}
public String getColor()
{
return color;
}
public abstract void setTerms();
public abstract void displayInfo();
}
//=========================================
public class Car extends MotorVehicle
{
String transType="";
String vehicleType;
String brand;
String color;
String terms;
int price = 0;
public Car(String vcl, String brn, String clr, String trm)
{
super(vcl, brn, clr, trm);
vehicleType = vcl;
brand = brn;
color = clr;
terms = trm;
}
public void Car()
{
brand = "Mazda";
vehicleType = "Sedan";
color = "Red";
transType = "Automatic";
price = (int) (700000 + (700000*0.2));
Double.toString(price);
terms = "5";
}
public void setTerms()
{
return;
}
public void displayInfo()
{
System.out.println("Brand is " + brand);
System.out.println("Vehicle type is " + vehicleType);
System.out.println("Color is " + color);
System.out.println("Transmission type is " + transType);
System.out.println("Price is " + price);
System.out.println("Terms is " + terms + " years to pay");
}
}
//=================================
public class Truck extends MotorVehicle
{
double payLoad=0.0;
String vehicleType;
String brand;
String color;
String terms;
int price = 0;
public Car(String vcl, String brn, String clr, String trm)
{
super(vcl, brn, clr, trm);
vehicleType = vcl;
brand = brn;
color = clr;
terms = trm;
}
public void Truck()
{
brand = "Isuzu";
vehicleType = "Truck";
color = "White";
payLoad = 3.5;
Double.toString(payLoad);
price = (int) (700000 + (700000*0.3));
Double.toString(price);
terms = "3";
}
public void setTerms()
{
return;
}
public void displayInfo()
{
System.out.println("Brand is " + brand);
System.out.println("Vehicle type is " + vehicleType);
System.out.println("Color is " + color);
System.out.println("Payload capacity is " + payLoad);
System.out.println("Price is " + price);
System.out.println("Terms is " + terms + " years to pay");
}
}
//==========================
public class Van extends MotorVehicle
{
int numPassenger=0;
String vehicleType;
String brand;
String color;
String terms;
int price=0;
public Van(String vcl, String brn, String clr, String trm)
{
super(vcl, brn, clr, trm);
vehicleType = vcl;
brand = brn;
color = clr;
terms = trm;
}
public void Van()
{
brand = "Mitsubishi";
vehicleType = "Family Van";
color = "Blue";
numPassenger = 8;
String.valueOf(numPassenger);
price = (int) (700000 + (700000*0.5));
Double.toString(price);
terms = "7";
}
public void setTerms()
{
return;
}
public void displayInfo()
{
System.out.println("Brand is " + brand);
System.out.println("Vehicle type is " + vehicleType);
System.out.println("Color is " + color);
System.out.println("Number of passenger is " + numPassenger);
System.out.println("Price is " + price);
System.out.println("Terms is " + terms + " years to pay");
}
}
//===================
And this is the main program:
public class MainVehicle
{
public static void main(String[] args)
{
BBVehicle[] vhl= new BBVehicle[3];
int ctr=0;
while(ctr<3)
{
if (ctr==0)
vhl[ctr]=new Car();
else if(ctr==1)
vhl[ctr]= new Truck();
else
vhl[ctr]= new Van();
vhl[ctr].displayInfo();
ctr++;
}
}
}
I'm not sure with what's wrong with my program. help me please thanks
i)
public void Car()
public void Truck()
public void Van()
You are defining return type of Class Contructor
it should be
public Car()
public Truck()
public Van()
A constructor resembles an instance method, but it differs from a method in that it has no explicit return type, it is not implicitly inherited and it usually has different rules for scope modifiers.
ii) Define a no-argument constructor in the abstract class (From the comment)
iii)
BBVehicle[] vhl= new BBVehicle[3];
int ctr=0;
while(ctr<3)
{
if (ctr==0)
vhl[ctr]=new Car();
You are casting Car class to BBVehicle class. Although, both class are different. There is no relation between these two class..
The first piece of advice I would give is that you shouldn't hide your member variables from your superlcass.
In each of your child classes, you declare variables with the same name as the private variables that you define in your super class. Instead, you should simply remove the duplicates from the child classes and either:
change the visibility of the variables in the superclass to something that makes them available to child classes (ie protected)
utilize getters to access them in your displayInfo() method. To do this you would need to set a get[VariableName]() per field in your superclass.