OOP Inheritance homework (Animal to lion super class inheritance) [closed] - java

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
I need to:
Extend the animal class with a Lion class and have different features(done).
Add a field called Liontype class and add a method classifying the lion type per its weight.(Needs to be derived from the superclass)
And print it out.
There are errors in my code and I've been trying to fix it.
Thank for any assistance in advance.
public class Animal {
private int numTeeth = 0;
private boolean spots = false;
private int weight = 0;
public Animal(int numTeeth, boolean spots, int weight){
this.setNumTeeth(numTeeth);
this.setSpots(spots);
this.setWeight(weight);
}
public int getNumTeeth(){
return numTeeth;
}
public void setNumTeeth(int numTeeth) {
this.numTeeth = numTeeth;
}
public boolean getSpots() {
return spots;
}
public void setSpots(boolean spots) {
this.spots = spots;
}
public int getWeight() {
return weight;
}
public void setWeight(int weight) {
this.weight = weight;
}
}
//Extend animal class
public class Lion extends Animal{
public Lion (int numTeeth, boolean spots, int weight){
super(numTeeth, spots, weight);
//Add new attributes
int age = 0;
int cubs = 0;
}
public static void main(String args[]){
//Create lions and assign attributes
Lion lion1 = new Lion();
lion1.numTeeth = 12;
lion1.spots = 1;
lion1. weight = 86;
lion1.age = 7;
lion1.cubs = 3;
//Print attributes
System.out.println("Lion1 attributes:");
System.out.println("Number of teeth : " + numTeeth);
System.out.println("Number of spots : " + spots);
System.out.println("Weight of lion : " + weight + " kgs");
System.out.println("Age : " + age);
System.out.println("No of cubs : " + cubs);
System.out.println(" ");
Lion lion2 = new Lion();
lion2.numTeeth = 16;
lion2.spots = 0;
lion2. weight = 123;
lion2.age = 13;
lion2.cubs = 5;
System.out.println("Lion2 attributes:");
System.out.println("Number of teeth : " + numTeeth);
System.out.println("Number of spots : " + spots);
System.out.println("Weight of lion : " + weight + " kgs");
System.out.println("Age : " + age);
System.out.println("No of cubs : " + cubs);
System.out.println(" ");
}
public class Liontype{
//Trying to get weight from another class
public Integer getWeight()
{
if (weight > 120)
{
System.out.println("This lion is a cub");
}
else if (weight >= 120 && weight < 180)
{
System.out.println("This lion is a female");
}
else if (weight >= 180)
{
System.out.println("This lion is a male");
}
}
}
}
Expected outcome:
Lion attributes:
Number of teeth : 16
Spots : true
Weight of lion : 83kgs
Age : 13
No of cubs : 3
This lion is a female

In addition to errors pointed out by Dmitry, your main in the Lion class has the following:
public static void main(String args[]){
//Create lions and assign attributes
Lion lion1 = new Lion();
lion1.numTeeth = 12;
lion1.spots = 1;
lion1. weight = 86;
lion1.age = 7;
lion1.cubs = 3;
numTeeth spots weight and all the other fields are set private. Your Lion class can't access these fields directly. You are supposed to use your getters and setters you from the Animal
Also when printing attributes in Lion:
//Print attributes
System.out.println("Lion1 attributes:");
System.out.println("Number of teeth : " + numTeeth);
System.out.println("Number of spots : " + spots);
System.out.println("Weight of lion : " + weight + " kgs");
System.out.println("Age : " + age);
System.out.println("No of cubs : " + cubs);
System.out.println(" ");
your fields are attributes to an object. Trying to print the fields directly will give you an compiler error because those are properties of your Lion1 object. You need to use the dot operator like this:
System.out.println("Number of Teeth" + Lion1.getNumTeeth());

Yes, there are many problems in your code that will be obtained at the compilation stage. Perhaps you incorrectly specified your examples. So, please provide details of your problem.
I will point out some that are immediately evident:
You declared local variables
int age = 0;
int cubs = 0;
in the constructor that doesn't actually extend the class Lion with new attributes. Add these attributes as a fields as you did to the class Animal:
private int age = 0;
private int cubs = 0;
and then initialize them in the constructor of the class Lion (if necessary).
In the method public static void main(String args[]), you are trying to use
Lion class fields age, cubs that it does not have. See point 1.
The public Integer getWeight() of the class Liontype has 2 errors. Firstly, the variable weight is not defined, and secondly there is missing the return statement, although the method must return a Integer value.

Related

Different values for each subclass

I would like to create a school(Houses) with 4 subclasses that take a basic values from the superclass(color, logo etc, each subclass with different values) and keep track, each sub class to itself of the number of students and points.
I also want to grant the ability to add points only for instance of Houses directly.
This is the code:
public class Houses {
int students = 75;
String color;
String logo;
String Founder;
String Trait;
String name;
int points = 0;
protected void Welcome() {
System.out.println("Welcome to " + name + "! \n This house was founded by " +
Founder + " and his core value is " + Trait + " , the house logo is " + logo
+ " and his color is " + color + "\n We have right now " + students + " students and "
+ points + " points. BEST OF LUCK!");
}
public void AddPoints(int x){
points += x;
System.out.println(x + " Points added!\nYour house now have " + points + " points");
}}
public class Gryffindor extends Houses {
Gryffindor() {
name = "Gryffindor";
students += 1;
color = "Red";
logo = "Lion";
Founder = "Godric Gryffindor";
Trait = "Brave";
Welcome();
}}
if im making the students and point as static its working fine but of course it add up all the sub classes together.
the best idea is to declare the values students and points inside each subclass as static?
Thanks for your time!
Looks like a misuse of sub-classes. Unless each sub-class is going to have it's own unique functionality, then each set of data should be associated to an instance of a House. You'd then most likely want to use the Constructor to set this data.
House Class
public class House {
int students;
String name;
String color;
//Other class variables
public House(int students, String name, String color) {
this.students = students;
this.name = name;
this.color = color;
}
//Various methods
}
Main Class
public class HouseTest {
public static void main(String[] args) {
House gryffindor = new House(75, "Gryffindor", "Red");
House ravenclaw = new House(68, "Ravenclaw", "Blue");
}
}
However, if you really want to set this data using a sub-class you can make use of the House constuctor via the super keyword which calls the parent constructor. Using the House from my code above it would be:
Gryffindor Class
public class Gryffindor extends House {
public Gryffindor() {
super(75, "Gryffindor", "Red");
//Set value for anything unique to Gryffindor here after super keyword
}
//Gryffindor specific methods
}
I will use a singleton School class to keep a single state count of students and points throughout the program. So create a class with those values you want to keep a single state track of and make them the class fields.
A singleton is a class that is instantiated once in memory and have the object shared by all classes within the application. This single state object in memory hold single state data points.
public class School{
private int students = 75;
private int points = 0;
private static final School instance = new School();
private School() {}
public static School getInstance() { return instance; }
public synchronized void addStudent() {
students++;
}
public synchronized void addPoints(int x) {
points += x;
}
public synchronized int getStudents() { return students; }
public synchronized int getPoints() { return points; }
}
So your House class will look like:
public class Houses {
School school = School.getInstance();
int students = school.getStudents();
String color;
String logo;
String Founder;
String Trait;
String name;
int points = school.getPoints();
protected void Welcome() {
System.out.println("Welcome to " + name + "! \n This house was founded by " +
Founder + " and his core value is " + Trait + " , the house logo is " + logo
+ " and his color is " + color + "\n We have right now " + students + " students and "
+ points + " points. BEST OF LUCK!");
}
public void AddPoints(int x){
school.addPoints(x);
System.out.println(x + " Points added!\nYour house now have " + points + " points");
}}
And your Gryffindor class
public class Gryffindor extends Houses {
Gryffindor() {
name = "Gryffindor";
school.addStudent();
color = "Red";
logo = "Lion";
Founder = "Godric Gryffindor";
Trait = "Brave";
Welcome();
}}

Need a way to associate strings with individual array elements

I am a complete beginner in programming and I'm working on a program for my mother that tracks her employee's monetary intake through a "horse race", with each employee having a horse and the program tracking their input to a UI made to look like a racetrack. After the help from my last inquiry, I've greatly simplified my mess of code but I am now faced with a new problem in that, after sorting the values largest to smallest, I have no way of associating the sorted values with the correct horse. I understand this explanation is confusing so I hope my code will do most of the talking for me here.
I honestly have no idea where to start with this. As I said in my last inquiry, I'm a complete beginner and severely lack the terminology or knowledge to find an answer here.
public class HorseRace {
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
String horse1 = "#5 Gitty-Up";
String horse2 = "#7 Lady Simmons";
String horse3 = "#6 Burning Peanutbutter";
String horse4 = "#10 White Lightning";
String horse5 = "#3 Bella";
String horse6 = "#1 Meg The Stallion";
float h1val;
float h2val;
float h3val;
float h4val;
float h5val;
float h6val;
System.out.println("Input amount for " + horse1 + ":");
h1val = sc.nextFloat();
System.out.println("Input amount for " + horse2 + ":");
h2val = sc.nextFloat();
System.out.println("Input amount for " + horse3 + ":");
h3val = sc.nextFloat();
System.out.println("Input amount for " + horse4 + ":");
h4val = sc.nextFloat();
System.out.println("Input amount for " + horse5 + ":");
h5val = sc.nextFloat();
System.out.println("Input amount for " + horse6 + ":");
h6val = sc.nextFloat();
Float[] values = new Float[]{h1val, h2val, h3val, h4val, h5val, h6val};
Arrays.sort(values, Collections.reverseOrder());
//currently displays horses with the wrong number. Need a way to tie the horse name strings to their respective float elements
System.out.println("The current race progress is :");
System.out.println(horse1 + " with $" + values[0]);
System.out.println(horse2 + " with $" + values[1]);
System.out.println(horse3 + " with $" + values[2]);
System.out.println(horse4 + " with $" + values[3]);
System.out.println(horse5 + " with $" + values[4]);
System.out.println(horse6 + " with $" + values[5]);
}
}
my desired result is printing the correct horse with the correct value. For example, if I put that #5 brought in $11 and #7 brought in $14, the program would print that #7 is in the lead with $14 and #5 is in second place with $11.
Currently, the program always prints #5 as being in the lead with the highest value, #7 being in second with the second highest, etc.
I understand this is because I am hard calling the horse1-horse6 values meaning they don't change, but these are acting more as placeholders while I figure out how to associate the right horse with the right value
This is where you should create a Horse class and store the data as instances of Horse.
class Horse {
private String name;
private float value;
public String getName() { return name; }
public float getValue() { return value; }
public void setName(String name) { this.name = name; }
public void setValue(float value) { this.value = value; }
}
And then in your main method:
Horse[] horses = new Horse[6] {
new Horse(), new Horse(), new Horse(), new Horse(), new Horse(), new Horse()
};
horses[0].setName("#5 Gitty-Up");
horses[1].setName("#7 Lady Simmons");
horses[2].setName("#6 Burning Peanutbutter");
// and so on...
// you should use a for loop here instead of writing similar lines over and over again!
for (int i = 0 ; i < 6 ; i++) {
System.out.println("Input amount for " + horses[i].getName() + ":");
horses[i].setValue(sc.nextFloat());
}
Arrays.sort(horses, Comparator.comparingDouble(Horse::getValue).reversed());
System.out.println("The current race progress is :");
for (int i = 0 ; i < 6 ; i++) {
System.out.println(horses[i].getName() + " with $" + horses[i].getValue());
}
By using a class, you are essentially grouping data that belongs together, together. On the line Arrays.sort(horses, Comparator.comparingDouble(Horse::getValue).reversed());, I am sorting the whole array of horses together, by their values.
If the concepts of classes and objects are new to you, that just means it's time to learn about some new concepts. Classes and objects are very important.
Step 1, create a Horse class. It should have two fields, amount and name. It should implement Comparable because you want to sort it. And looking at your desired output, I would override toString().
class Horse implements Comparable<Horse> {
private String name;
private float amount;
public Horse(String name, float amount) {
this.name = name;
this.amount = amount;
}
#Override
public String toString() {
return String.format("%s with $%.2f", name, amount);
}
#Override
public int compareTo(Horse o) {
return Comparator.comparing((Horse h) -> h.amount)
.thenComparing((Horse h) -> h.name).compare(this, o);
}
}
Step 2, create an array of horseNames and iterate that populating an array of Horses (with amounts). Then sort it, and I would prefer Comparator.reverseOrder() to Collection.reverseOrder() when sorting an array.
public static void main(String[] args) throws Exception {
Scanner sc = new Scanner(System.in);
String[] horseNames = { "#5 Gitty-Up", "#7 Lady Simmons",
"#6 Burning Peanutbutter", "#10 White Lightning",
"#3 Bella", "#1 Meg The Stallion" };
Horse[] horses = new Horse[horseNames.length];
for (int i = 0; i < horseNames.length; i++) {
System.out.printf("Input amount for %s:%n", horseNames[i]);
float amt = sc.nextFloat();
horses[i] = new Horse(horseNames[i], amt);
}
Arrays.sort(horses, Comparator.reverseOrder());
System.out.println("The current race progress is :");
for (int i = 0; i < horses.length; i++) {
System.out.println(horses[i]);
}
}

How do i assign and obtain values to objects created in an array?

Currently learning Java as a hobby and am making small game projects to reinforce the concepts. So for this one, I've made a method that creates an array of objects, in this case, a "Computer" object. I'm doing this because I want the user to decide at startup how many computer opponents they want to play against, instead of hard coding a set number of them. Now I want to assign and retrieve a value for each Computer object. For example a Computer name, bet amount, and a dice roll guess.
public class Computer {
static int bet;
static int guess;
int cash;
static Computer[] c;
public static void create(int numComps) {
c = new Computer[numComps];
for (int i = 0; i < numComps; i++) {
c[i] = new Computer();
c[i].cash = Game.startCash;
c[i].bet = bet();
c[i].guess = guess();
c[i].display();
}
}
public static int bet() {
bet = Rng.rand(Game.startCash / 50) * 50;
return bet;
}
public static int guess() {
guess = Dice.roll();
return guess;
}
public void display() {
String name = "Computer ";
System.out.println("My name is " + name + " i bet " + bet + " and guess " + guess);
}
}
When i do Computer.create(5) i get
My name is Computer i bet 150 and guess 9
My name is Computer i bet 50 and guess 3
My name is Computer i bet 450 and guess 11
My name is Computer i bet 250 and guess 11
My name is Computer i bet 50 and guess 10
This output gives the appearance of working but i don't think i'm on the right track. For the name i want the syntax to be something like, name = "Computer " + c[i]. Resulting in "Computer 1", "Computer 2", "Computer 3" etc, not sure how to do that correctly. And an individual bet and guess to be assigned to each individual object. Right now i think its just displaying a random number rather than assigning that value to the particular object.
The bet and guess member variables shouldn't be static.
To display the id you can add a new int member variable, set it to i for each computer when you initialize them in the loop, and update the display() method to print it.
public class Computer {
int id;
int bet;
int guess;
int cash;
static Computer[] c;
public static void create(int numComps) {
c = new Computer[numComps];
for (int i = 0; i < numComps; i++) {
c[i] = new Computer();
c[i].id = i;
c[i].cash = Game.startCash;
c[i].bet = bet();
c[i].guess = guess();
c[i].display();
}
}
public static int bet() {
return Rng.rand(Game.startCash / 50) * 50;
}
public static int guess() {
return Dice.roll();
}
public void display() {
String name = "Computer ";
System.out.println("My name is " + name + id + " bet " + bet + " and guess " + guess);
}
}

Using arrays for user input

I've looked around for answers for this but I cannot find it. My professor requires me to use an array.. not an arraylist
public static void main(String[] args) {
final int total = 30;
String[] animalType = new String[total];
Scanner input = new Scanner(System.in);
for (int x = 0; x < total; x++) {
System.out.println("Enter the type of animal " + x + 1);
animalType[x] = input.next();
for (int x1 = 0; x1 < total; x1++) {
System.out.println("Enter the weight of the animal " + (x1 + 1));
animalType[x1] = input.next();
}
input.close();
System.out.println("Your friends are");
for (int counter = 0; counter < total; counter++) {
System.out.println(animalType[counter] + "\n" + animalType[counter]);
}
}
}
The prompt is.. allow user to enter the type of the animal and the weight of the animal and then output the average weight by animal type.
I'm new to java and do not know how to use arrays properly.
I think you should create a class for this purpose.
First, create another file called Animal.java and write a class that stores a type and a weight:
public class Animal {
public String type;
public int weight;
}
Of course, it would be better if you add getters and setters, but that would be too hard for you I think. I'll show the code anyways, but I won't use it in the example below.
public class Animal {
private String type;
private int weight;
public String getType() {return type;}
public void setType(String value) {type = value;}
public int getWeight() {return weight;}
public void setWeight(int value) {weight = value;}
}
Now you have this class, you can create an array of it.
Animal[] animals = new Animal[total];
And you need to fill the array in with animals!
for (int i = 0 ; i < total ; i++) {
animals[i] = new Animal();
}
Actually, your for-loops are wrong. If you want to ask the user for the type first, then the weight, you should do it like this:
for (int x = 0; x < total; x++) {
System.out.println("Enter the type of animal " + x + 1);
animals[x].type = input.next();
}
for (int x1 = 0; x1 < total; x1++) {
System.out.println("Enter the weight of the animal " + (x1 + 1));
animals[x1].weight = Integer.parseInt(input.next());
}
Now you got the types and weights of the animals, hooray!
You need a second array to store the weight(s). Something like
String[] animalWeight = new String[total];
for(int x1 = 0; x1 < total; x1++){
System.out.println("Enter the weight of the animal "+(x1+1));
animalWeight[x1] = input.next();
}
Next, you print the values from your two arrays. And I would prefer calling println twice to embedding a \n (on some systems that can also cause issues, because they use other line termination characters such as \r\n). That might look something like,
// input.close(); // <-- Also closes System.in, can cause subtle bugs.
System.out.println("Your friends are");
for(int counter = 0; counter < total; counter++){
System.out.println(animalType[counter]);
System.out.println(animalWeight[counter]);
}

Few questions about objects in JAVA

I am quite new to programming and my assignment this week is based around objects in java.
Before anything here are my codes
public class Animal {
float mass;
String name;
int legs;
// Exercise 6-6
public Animal(String randomName) {
name = randomName;
legs = 0;
mass = 0;
}
// Exercise 6-7
public Animal(float one, String two, int three) {
mass = one;
name = two;
legs = three;
}
//Exercise 7
public String toString(){
return "name =" + name + "legs=" + legs + "mass=" + mass;
}
public void massSetter() {
}
public String getName() {
return name;
}
public int getLegs() {
return legs;
}
}
Then there is this one
public class Zoo {
private Animal[] park;
// Exercise 9
public Zoo() {
Animal[] park = new Animal[10];
}
// Exercise 10
public void addAnimal(Animal first) {
for (int i = 0; i < 10; i++) {
if (park[i] != null) {
park[i] = first;
i = 10;
} else if (i == 9) {
System.out.println("The zoo is full!");
}
}
}
// Exercise 11
public void feed() {
for (int i = 0; i < 10; i++) {
park[i].mass *= 1.1;
}
}
public String toString() {
return "The zoo is capable of keeping " + park.length + "animals"
+ '\n'
+ "The following is the list of animals currently in the zoo."
+ '\n' + "cage 1 status: " + park[0] + '\n' + "cage 2 status: "
+ park[1] + '\n' + "cage 3 status: " + park[2] + '\n'
+ "cage 4 status: " + park[3] + '\n' + "cage 5 status: "
+ park[4] + '\n' + "cage 6 status: " + park[5] + '\n'
+ "cage 7 status: " + park[6] + '\n' + "cage 8 status: "
+ park[7] + '\n' + "cage 9 status: " + park[8] + '\n'
+ "cage 10 status: " + park[9];
}
public void print() {
System.out.println(park.toString());
}
public int totalLegs() {
int totalLeg = 0;
for (int i = 0; i < 10; i++) {
totalLeg += park[i].legs;
}
return totalLeg;
}
}
and finally
public class TestZoo {
public static void main(String[] args){
Zoo zoo = new Zoo();
}
}
I have two questions.
First of all as you can see from the toString method in Zoo class, my return statement is way too long. I tried using for loop but i seems i cant really do that in a return statement so I was wondering if there is any simpler way.
The second question is that the exercise tells me to fill up the object zoo that I made in the TestZoo class with names like elephant and spider. I was wondering how i could do this.
1) You can use StringBuilder and loop to build a string. See docs here.
2) You have method addAnimal(Animal first) for adding animal to zoo.
First of all as you can see from the toString method in Zoo class, my return statement is way too long. I tried using for loop but i seems i cant really do that in a return statement so I was wondering if there is any simpler way.
public String toString() {
String str = "The zoo is capable of keeping " + park.length + "animals\nThe following is the list of animals currently in the zoo.";
for(int i = 0; i < park.length; i++)
str += '\n' + "cage " + i + " status: " + park[i];
return str;
}
The second question is that the exercise tells me to fill up the object zoo that I made in the TestZoo class with names like elephant and spider. I was wondering how i could do this.
public class TestZoo {
public static void main(String[] args){
Zoo zoo = new Zoo();
Animal spider = new Animal("spider");
zoo.addAnimal(spider);
}
}
If you've got a lot of animals, the above method won't actually be feasible. So create an array of Strings (Strings because you need one to make an Animal)
String[] arr = {"Spider", "Elephant"};
And then add create an animal for each of the string, and add the animal
for(int i = 0; i < arr.length; i++)
{
Animal a = new Animal( arr[0] );
zoo.addAnimal(a);
}
OR just
for(int i = 0; i < arr.length; i++)
zoo.addAnimal(new Animal(arr[0]));
The toString is like any other method. You can create variables.
String value = "The zoo is capable of keeping " + park.length + "animals";
value =value + '\n'; // etc
return value;
Somthing like
zoo.add(new Animal("zebra"));
For your toString(): Use a StringBuilder with a for-loop in conjuction with String.format() instead to greatly reduce the length.
The loop is important since you're basically echoing the contents of the entire array. Be sure that Animal has overridden toString() to provide valuable information about the instance.
public String toString() {
StringBuilder ret = new StringBuilder("The zoo is capable of keeping " + park.length + "animals");
ret.append("\n");
ret.append("The following is the list of animals currently in the zoo.");
for(int i = 0; i < park.length; i++) {
ret.append(String.format("\ncage %d status : " + park[i].toString()));
}
return ret.toString();
}
To fill your zoo, given the constructor for Animal, I would presume that passing the name "spider" would suffice.
Animal spider = new Animal("spider");
Zoo zoo = new Zoo();
zoo.addAnimal(spider);
Q1: ...return statement is too long...no way to do that in a return statement
A: do it separately. Build the display String (or StringBuilder) in a loop, then return the result.
Q2: ...fill up the object zoo
A: you'll need to create new animals and call addAnimal once for each.
An initialized array of animal names and a for-loop might help:
String names[]= {"aardvark", "bison", "cat", "dog", "eagle", "elephant", "giraffe", "horse", "owl", "emu"};
You can do something like this:
String result = "The list:\n";
for (int i = 0; i< 10; i++) {
result = result + "cage " + i + " status:" + park[i] + "\n";
}
return result;
Here "+" concatenates adjacent strings, and you build up the total result one line at a time.
But using string concatenation is somewhat inefficient (though perfectly adequate for toString in most cases, since that's usually for diagnostics), so many times it's better to use something like StringBuilder, especially for main-line "production" methods.

Categories

Resources