compare constructors objects Java - java

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

Related

How do you update/change a instance variable in Java? (Beginner Level)

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

java Output does not match input for variables

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;

How to let an Animal object know what Room it is in through a reference

I am working with two separate classes, Animal and Room. A Room is instantiated with an array within. Animal objects are then instantiated and placed in the array within the Room. How can I give the Animal objects a reference to what Room they are placed into so when I call a look() method on them, they can return the name of the Room they are in?
public static void main(String[] args) {
Room mainRoom = new Room("The Lobby");
Animal gizmo = new Animal("Gizmo");
mainRoom.addAnimal(gizmo);
System.out.println(mainRoom.toString());
gizmo.look();
}
-
public class Room {
private String name;
private Animal[] animals;
private Room currentRoom;
int i = 0;
public Room(String name) {
setName(name);
animals = new Animal[10];
}
public String toString() {
String temp = new String();
temp += "\nThis room is " + name + ".\n\n";
temp += "In the lobby are the following animals: \n";
for (Animal s : animals) {
temp += s.toString() + "\n";
}
return temp;
}
public void setName(String name) {
this.name = name;
}
public void addAnimal(Animal a) {
if (i < 10) {
if (animals[i] != null) {
i++;
addAnimal(a);
} else {
animals[i] = a;
}
} else {
System.out.println("Room full");
}
}
}
-
public class Animal {
private Room currentRoom;
private String name;
public Animal() {
}
public Animal(String name) {
setName(name);
}
public void setName(String name) {
this.name = name;
}
public String toString() {
return "\t" + name;
}
public void look() {
System.out.println(name + " is currently in " + getCurrentRoom());
//getCurrentRoom().toString();
}
public Room getCurrentRoom() {
return this.currentRoom;
}
public void setCurrentRoom(Room currentRoom) {
this.currentRoom = currentRoom;
}
}
How can I give the Animal objects a reference to what Room they are
placed into so when I call a look() method on them, they can return
the name of the Room they are in?
You should set the room within Animal instead:
Animal gizmo = new Animal("Gizmo");
gizmo.setCurrentRoom(mainRoom); // this would set mainRoom as the attribute of gizmo
Further your code here:
public void look() {
System.out.println(name + " is currently in " + getCurrentRoom());
//getCurrentRoom().toString();
}
would fetch the currentRoom as set by the code above.
I think the most elegant solution will be inside the addAnimal function of the Room like this
public void addAnimal(Animal a) {
if (i < 10) {
if (animals[i] != null) {
i++;
addAnimal(a);
} else {
animals[i] = a;
a.setCurrentRoom(this); // Setting room of animal
}
} else {
System.out.println("Room full");
}
}
gizmo.setCurrentRoom(mainRoom);
(If construct Animal object within Room use : gizmo.setCurrentRoom(this))
You could also add String getRoomName() {return currentRoom.getName();} to Animal class.

Syntax on printing objects? [closed]

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

The type of the expression must be an array type but it resolved to

Im new to java. I dont understand why these errors are occurring. trying to make an array list so that it saves each object. The errors im getting are The type of the expression must be an array type but it resolved to ArrayList on the line 'newbug1[i].setspecies();'
Thankyou in advance
import javax.swing.JOptionPane;
import java.util.ArrayList;
public class Abug2 {
private String species;
private String name;
private char symbol = '\0';
private int horposition = 0, verposition = 0, energy = 0, uniqueID = 1, counter;
public Abug2(String species, String name, char symbol)
{
uniqueID = counter;
counter++;
}
public void setspecies(){
species = JOptionPane.showInputDialog(null, "Enter the species: ");
}
public String getspecies(){
return species;
}
public void setname(){
name = JOptionPane.showInputDialog(null, "Enter the name: ");
}
public String getname(){
return name;
}
public void setsymbol(){
symbol = name.charAt(0);
}
public char getsymbol(){
return symbol;
}
public int getid(){
return uniqueID;
}
public int gethorizontal(){
return horposition;
}
public int getvertical(){
return verposition;
}
public int getenergy(){
return energy;
}
//The class ABug has a set of methods: two or more constructors, toString, toText, and getters and setters for the attributes
public String toString(){
String tostring = "\nName: " + name + "\nHorizontal Position: " + horposition + "\nVertical Position: " + verposition + "\n";
return tostring;
}
public String toText(){
String totext = getspecies() + getname() + getsymbol() + getid() + gethorizontal() + getvertical() + getenergy();
return totext;
}
public static void main (String [] args){
ArrayList<Abug2> newbug1 = new ArrayList<Abug2>();
String choice = JOptionPane.showInputDialog(null, "Would you like to add another bug?: ");
do{for (int i = 0; i < 3; i++) {
newbug1.add(new Abug2("Bug", "Spider", 's'));
newbug1[i].setspecies();
newbug1[i].setname();
newbug1[i].setsymbol();
System.out.println(newbug1[i].toString());
} }while(choice != "yes");
}
}
For arraylists use get() instead:
newbug1.get(i).setspecies();
newbug1.get(i).setname();
newbug1.get(i).setsymbol();
Because it stores object references any setFoo calls affect the original object referenced in the arraylist.
In order to access an element in an ArrayList you have to use a method called get.
In your code, replace newbug1[i] by newbug1.get(i)
And moreover, you should store that reference in a variable instead of recalling it again and again:
Abug2 currentBug = newbug1.get(i);
currentBug.setSpecies();
Your code will gain in clarity.

Categories

Resources