I am trying to have a user select an animal from my virtualZoo.java file when it runs. It compiles, but once the user inputs a selection I get an error that reads "Erroneous tree type." The code is below for virtualZoo.java, animal.java, and dog.java. I have created objects below the switch statement as I was instructed to use those, but do not understand the implementation.
virtualZoo.java
import java.util.Scanner;
public class VirtualZoo{
public static void main(String[] args) {
Animal cat = new Animal("Cat", "Meow");
Animal dog = new Animal("Dog", "Woof");
Animal duck = new Animal("Duck", "Quak");
// create Scanner
Scanner input;
input = new Scanner(System.in);
double userInput;
System.out.println("Welcome to the Zoo");
System.out.println("Pick select an animal to visit");
System.out.println("=================================");
System.out.println("===========MAIN MENU=============");
System.out.println("=================================");
System.out.println("== 0) Cat ===================");
System.out.println("== 1) Dog ===================");
System.out.println("== 2) Duck ===================");
System.out.println("== -1) EXIT ===================");
System.out.println("=================================");
System.out.println();System.out.println();
System.out.println( "Input : ");
Scanner sc = new Scanner(System.in);
userInput = sc.nextInt();
switch (sc.nextInt()) {
case 0:
System.out.println(cat);
break;
case 1:
System.out.println(dog);
break;
case 2:
System.out.println(duck);
break;
case -1:
System.out.println("Your name is short length.");
break;
default:
break;
}
duck.speak();
dog.speak();
cat.speak();
}
}
animal.java (Animal Class within virtualZoo.java)
public class Animal {
private String animalSound;
private String animalType = "";
//set animal sound
public void setSound(String sound) { this.animalSound = sound; }
//get animal sound
public String getSound() { return animalSound; }
public void setType(String type) { this.animalType = type; }
//get animal type
public String getType() { return animalType; }
public Animal(String animalType, String animalSound)
{
this.animalSound = "";
this.animalType = animalType;
this.animalSound = animalSound;
}
public void speak()
{
System.out.println("The " + animalType + " says " + animalSound);
}
}
dog.java (Dog class within Animal class)
public class Dog extends Animal {
public Dog(String animalType, String animalSound) {
super(animalType, animalSound);
}
#Override
public void speak(){
System.out.println("This dog barks");
}
}
You're on the right track but I believe you have some mistakes. I'm assuming the code you posted is slightly different from the code that's giving you the error (I tested, and didn't receive the error)
Here, you are getting 2 inputs from the user. I believe you meant to get just 1.
userInput = sc.nextInt();
switch (sc.nextInt())
Also, userInput should be on type int, not double.
You have a dog class, but no cat/duck class
It looks like you might be trying to use a factory pattern, but I'm not 100% sure. You could create an AnimalFactory class if so. Otherwise the class 'Animal' is confusing. I'll assume you are not using a Factory Pattern.
You'll notice a few things:
I override the toString() method from Object. System.out.println will invoke the toString() method.
Cat, Duck and Dog all extend from Animal, so your Animal animalSelected can be of any of these types!
Animal has 2 abstract methods. These methods Must be overriden in any sub classes (Cat, Dog, Duck). Having the methods declared Means we can use the methods inside the Animal class. It also allows us to invoke the methods on any Animals.
E.G you can use animalSelected.getAnimalSound() even though Animal does not define a body of that method.
import java.util.Scanner;
public class VirtualZoo
{
public static void main(String[] args)
{
// Options
final int catType = 0,
dogType = 1,
duckType = 2,
exit = -1;
// create Scanner
Scanner input;
input = new Scanner(System.in);
int userInput;
System.out.println("Welcome to the Zoo");
System.out.println("Pick select an animal to visit");
System.out.println("=================================");
System.out.println("===========MAIN MENU=============");
System.out.println("=================================");
System.out.println("== " + catType + ") Cat ===================");
System.out.println("== " + dogType + ") Dog ===================");
System.out.println("== " + duckType + ") Duck ===================");
System.out.println("== " + exit + ") EXIT ===================");
System.out.println("=================================");
System.out.println();
System.out.println();
System.out.println( "Input : ");
Scanner sc = new Scanner(System.in);
userInput = sc.nextInt();
Animal animalSelected = null;
switch (userInput)
{
case catType:
animalSelected = new Cat();
break;
case dogType:
animalSelected = new Dog();
break;
case 2:
animalSelected = new Duck();
break;
case -1:
System.out.println("Your name is short length.");
break;
default:
break;
}
if (animalSelected != null)
{
System.out.println(animalSelected);
}
}
}
public abstract class Animal
{
public abstract String getAnimalSound();
public abstract String getAnimalType();
#Override
public String toString()
{
return "The " + getAnimalType() + " says " + getAnimalSound();
}
}
public class Duck extends Animal
{
#Override
public String getAnimalSound()
{
return "quacks";
}
#Override
public String getAnimalType()
{
return "Duck";
}
}
public class Cat extends Animal
{
#Override
public String getAnimalSound()
{
return "meows";
}
#Override
public String getAnimalType()
{
return "Cat";
}
}
public class Dog extends Animal
{
#Override
public String getAnimalSound()
{
return "barks";
}
#Override
public String getAnimalType()
{
return "Dog";
}
}
Related
I have 7 classes(shown in pick below) with main method class for testing is Animalstuff class. When I'm running the code its getting hung and not moving any where. Need your help to solve this.At the end I want to run using Junit.
classes all
running Animalstuff class, see below it hang and not moving forward.
hung
here is the code for complete Animalstuff class.
/**
*
*/
import java.util.ArrayList;
import java.util.Scanner;
public class AnimalStuff {
// main function
public static void main(String[] args) {
// for taking inputs
Scanner in = new Scanner(System.in);
// arrayList to store all the animals
ArrayList<Animal> myList = new ArrayList<Animal>();
int ch;
// Loop until user chooses to quit
do {
// print menu
System.out.println("Menu");
System.out.println("1. Add animal");
System.out.println("2. Print");
System.out.println("3. Exit");
System.out.print("Enter your choice: ");
ch = in.nextInt();
// if user chooses to add animal to list
if(ch==1) {
// input the kind/name of animal
in.nextLine();
String word;
System.out.print("Enter name of animal: ");
word = in.nextLine();
// create object of that kind
Animal obj = Animal.newInstance(word);
// if user entered invalid animal, print message
if(obj==null) {
System.out.println("Animal doesn't exist.");
}
// else add to the list
else {
myList.add(obj);
}
}
// if user chooses to see information of all the
// animals in the list
else if(ch == 2) {
for(int i=0;i<myList.size();i++) {
myList.get(i).print(true);
}
}
// if user chooses to quit
else {
System.out.println("See you soon!");
}
}while(ch != 3);
}
}
Below is the code for Animal class
import java.util.ArrayList;
import java.util.Scanner;
public class Animal {
// variables
public String kind;
public String integument;
public boolean fast;
// private constructor to avoid plain animals
private Animal() {
}
// public argument constructor for Mammal and Bird class to
// call
public Animal(String kind, boolean fast) {
this.kind = kind;
this.fast = fast;
}
// movement method
public String movement() {
if(fast) {
return "I run on four legs.";
}
else {
return "I walk on four legs.";
}
}
// sound method
public String sound() {
return "";
}
// method to print all the information about the animal
public void print(boolean fast) {
String move = "";
if(fast)
move = "fast";
else
move = "slowly";
System.out.println("I am a "+kind);
System.out.println(" I have "+integument);
System.out.println(" When I go "+move+", "+movement());
System.out.println(" The sound I make is "+sound());
}
// method to return the animal object of type kind
public static Animal newInstance(String kind) {
Animal obj;
boolean correct = false;
if(kind.toLowerCase().equals("cow")) {
obj = new Cow();
Cow cow = new Cow();
if(obj.equals(cow)) {
correct = true;
}
}
else if(kind.toLowerCase().equals("duck")) {
obj = new Duck();
Duck duck = new Duck();
if(obj.equals(duck)) {
correct = true;
}
}
else if(kind.toLowerCase().equals("parrot")) {
obj = new Parrot();
Parrot parrot = new Parrot();
if(obj.equals(parrot)) {
correct = true;
}
}
else if(kind.toLowerCase().equals("whale")) {
obj = new Whale();
Whale whale = new Whale();
if(obj.equals(whale)) {
correct = true;
}
}
else {
return null;
}
if(correct) {
System.out.println("Correct object is formed.");
}
else {
System.out.println("Wrong object is formed.");
}
return obj;
}
// Function to check if two methods are same, i.e., this function
// checks whether the object formed is correct or not
public boolean equals(Animal obj) {
if(this.kind.equals(obj.kind)) {
if(this.integument.equals(obj.integument)) {
if(this.movement().equals(obj.movement())) {
if(this.sound().equals(obj.sound())) {
return true;
}
}
}
}
return false;
}
}
Please let me know whats worng in this and how I can fix. The other classes are very small if need I can give code for those as well.
Thanks
Enter your choice:
If you are getting this line in the console then it's asking for the input ch. Enter your input and you'll proceed further.
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.
So what I'm trying to achieve is that when I write a word like "Meat" at the request of the input, the method will check the relations, and will run the appropriate result for the word "Meat", like if is "Meat" is the input "woof" should be printed.But on execution nothing happens .I have to tell that I'm new to Java and programming. Thank you for patience!
package animals;
import java.util.Scanner;
public class Animal {
public int hungerLvl = 0;
public String food;
public String[] foodTypes = {"Meat" , "Grass", "Water"};
Scanner in = new Scanner(System.in);
public void eatFood(){
System.out.println("Enter food: ");
food = in.nextLine();
if(food == foodTypes[0].toString()){
System.out.println("woof");
hungerLvl++;
System.out.println("Hunger lvl incresead to " + hungerLvl);
} else {
if (food == foodTypes[1].toString()){
System.out.println("Animal is eating grass");
hungerLvl++;
}
if (food == foodTypes[2].toString()){
System.out.println("Animal is drinking water");
hungerLvl++;
}
}
}
//ignore this method :)
public int maxLvl(){
if(hungerLvl == 5){
System.out.println("No more food, going to take a nap!");
hungerLvl = hungerLvl - 5;
}
return 0;
}
public static void main(String[] args){
Animal animal = new Animal();
animal.eatFood();
}
}
Use str.equals or str.match
public void eatFood(){
System.out.println("Enter food: ");
food = in.nextLine();
if(food.matches(foodTypes[0])){
System.out.println("woof");
hungerLvl++;
System.out.println("Hunger lvl incresead to " + hungerLvl);
} else {
if (food.matches(foodTypes[1])){
System.out.println("Animal is eating grass");
hungerLvl++;
}
if (food.matches(foodTypes[2])){
System.out.println("Animal is drinking water");
hungerLvl++;
}
}
}
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 keep getting this error message
Error: Could not find or load main class Animals.Animals
Java Result: 1
I don't think I did anything wrong to my program. I can't even find where I did something wrong. Here's my program:
package Animals;
import java.util.*;
public class Animals {
private static final Scanner keyboard = new Scanner(System.in);
public static void introduction() {
System.out.println("WELCOME TO GUESS THE ANIMAL GAME");
System.out.println("If I am correct press Y and if I am wrong press N");
System.out.println("Ready? Let's begin!");
System.out.println("-------------------------------------------------");
}
public static void letsPlay(AnimalNode<String> latest) {
while (!latest.correct()) {
if (query(latest.getAnimal())) {
latest = latest.getleft();
} else {
latest = latest.getright();
}
}
System.out.println("Is it a " + latest.getAnimal());
if (!query("\nY or N?")) {
question(latest);
} else {
System.out.println("Winner!");
}
}
public static AnimalNode<String> AnimalTree() {
AnimalNode<String> root;
AnimalNode<String> child;
final String rootQuestion = "dog";
final String animal = "dog";
root = new AnimalNode<String>(rootQuestion, null, null);
return root;
}
public static void question(AnimalNode<String> latest) {
String setAnimal;
String correctAnimal;
String characteristic;
setAnimal = latest.getAnimal();
System.out.println("What is the correct answer? ");
correctAnimal = keyboard.nextLine();
System.out.println("What's a characteristic of " + correctAnimal
+ " that is different from " + setAnimal);
characteristic = keyboard.nextLine();
latest.setAnimal(characteristic);
System.out.println("A " + correctAnimal + characteristic);
if (query("Correct?")) {
latest.setLeft(new AnimalNode<String>(correctAnimal, null, null));
latest.setRight(new AnimalNode<String>(correctAnimal, null, null));
}
}
public static boolean query(String ask) {
String answer;
System.out.println(ask + "Y or N: ");
answer = keyboard.nextLine().toLowerCase();
while (!answer.startsWith("y") && !answer.startsWith("n")) {
System.out.println("Press the correct letter");
System.out.println("Let's try again");
}
return answer.startsWith("y");
}
public static void main(String[] args) {
AnimalNode<String> root;
introduction();
root = AnimalTree();
do {
letsPlay(root);
} while (query("-------------------------------------------------"
+ "\nPlay again?"));
}
}
The Animals class MUST be in the Animals directory...
\src
\Animals
Animals.java
It must have the package decleation of package Animals
package Animals;
// imports
public class Animals {
//...
You can compile it from within the Animals directory, but it would probably be safer to compile it in the parent directory...
javac -cp Animals Animals\*.java
You then need to use the fully qualified class name to run it (from the parent directly of Animals...)
java Animals.Animals