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.
Related
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";
}
}
So I want to create a menu where a user can choose to play two different games. I want to create a main method and be able to make a for loop or switch statements for the different game options or for the user to quit but I am not sure how I would call the classes so that the game runs when they choose it.
Can someone explain to me how I would go about this. Thanks!
import java.util.Scanner;
import java.util.Random;
public class RpsGame {
/* Valid user input: rock, paper, scissors */
public static void main(String[] args) {
System.out.print("Please Make Your Choice (Rock, Paper or Scissors): ");
try {
Scanner sc =
new Scanner(System.in);
String userInput =
sc.next();
if (isValid( userInput )) {
game( userInput );
} else {
print("Invalid user input!\nWrite rock, paper or scissors!");
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static void print(String text) {
System.out.println( text );
}
public static boolean isValid(String input) {
if (input.equalsIgnoreCase("rock")) {
return true;
}
if (input.equalsIgnoreCase("paper")) {
return true;
}
if (input.equalsIgnoreCase("scissors")) {
return true;
}
return false;
}
public static void game(String user) {
String computer = computerResults();
//System.out.print("Please Make Your Choice: ");
print( user + " vs " + computer + "\n");
if (user.equalsIgnoreCase(computer)) {
print("Oh, Snap! Tied - No winners.");
} else {
if (checkWin(user, computer)) {
print("You won against the computer!");
} else {
print("You lost against the computer!");
}
}
}
public static String computerResults() {
String types[] =
{"rock", "paper", "scissors"};
Random rand = new Random();
int computerChoice = rand.nextInt(3);;
return types[computerChoice];
}
public static boolean checkWin(String user, String opponent) {
if ( (!isValid( user )) && (!isValid( opponent )) ) {
return false;
}
String rock = "rock", paper = "paper", scissors = "scissors";
if ( (user.equalsIgnoreCase( rock )) && (opponent.equalsIgnoreCase( scissors )) ) {
return true;
}
if ( (user.equalsIgnoreCase( scissors)) && (opponent.equalsIgnoreCase( paper )) ) {
return true;
}
if ( (user.equalsIgnoreCase( paper )) && (opponent.equalsIgnoreCase( rock )) ) {
return true;
}
return false;
//If no possible win, assume loss.
}
}
The easiest method that I am familiar with is using something called a Driver Class. A Driver Class is a class that is designed to run code from other classes - perfect for running two different games. Check this post if you need more info: What is a driver class? (Java)
Try something like this:
public class MyGameApp {
public static final String OPTION_1 = "1";
public static final String OPTION_2 = "2";
public static final String OPTION_EXIT = "3";
public static void main(String... args) {
Scanner sc = new Scanner(System.in);
String userChoice = null;
do {
System.out.println("Choose an option: \n 1. Game 1\n2. Game 2\n3. Exit");
userChoice = sc.nextLine();
switch(userChoice) {
case OPTION_1:
/*
Calls a static method of a class, so there is no need of instantiate the class first.
*/
GameOne.start();
break;
case OPTION_2:
/*
In this case, create a new instance of the class GameTwo, and then call the method start().
*/
GameTwo game = new GameTwo();
game.start();
break;
default:
System.out.println("Wrong option, try again.");
}
while(!OPTION_EXIT.equals(userChoice));
}
}
class GameOne {
public static void start() { ... }
}
class GameTwo {
public void start() { ... }
}
I'm trying to write a game in Java with a Player class that has 2 subclasses: HumanPlayer and ComputerPlayer. I want to allow the user to choose which player to play against, and once chosen - to create the relevant object and play.
Since the object is created within an if statement, the compiler doesn't let me perform any operations outside the if scope. In other cases I would create the object within the class' scope but in this case I cant know in advance which object to create (human/computer)
Here is some code for illustration:
public class Player {
private String name;
public String getName(){
return name;
}
}
public class HumanPlayer extends Player {
public void play(){
System.out.println("Human playing");
}
}
public class ComputerPlayer extends Player {
public void play(){
System.out.println("Computer playing");
}
}
import java.util.Scanner;
public class PlayerDriver {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Please type 1 for human, 2 for computer");
int selection = in.nextInt();
if (selection==1){
HumanPlayer player = new HumanPlayer();
} else if (selection==2){
ComputerPlayer player = new ComputerPlayer();
} else {
throw new IllegalArgumentException("invalid answer");
}
Player.play(); //can't do that
}
}
Harness the power of polymorphism
Player player = null; // player should never be null as you would have thrown an exception, but for the sake of completeness
if (selection == 1){
player = new HumanPlayer();
} else if (selection == 2){
player = new ComputerPlayer();
} else {
throw new IllegalArgumentException("invalid answer");
}
player.play();
assuming the Player class has a play() method. I see it doesn't. Change your class Player to have an override-able play() method which you override in the sub types.
I keeping running into this problem with my setInner method where if I keep it as telling me that "The method setInner(GList) in the type InnerList is not applicable for the arguments (Integer)". Which seems odd to me because it seems like an Integer would be applicable to a GList. Can someone help me figure out what I'm doing wrong?
My Inner Class where a list of integers 'inner' will be stored.
public class InnerList {
private String name;
private GList<Integer> inner = new GList<Integer>();
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public GList<Integer> getInner() {
return inner;
}
public void setInner(GList<Integer> inner) {
this.inner = inner;
}
}
The portion of my public class that is causing me problems, within my main method:
GList<InnerList> list = new GList<InnerList>();
InnerList iList = new InnerList ();
Scanner sc = new Scanner(System.in);
String answer;
while (true) {
System.out.println("Do you want to enter a number (y/n)?");
answer = sc.nextLine();
if (answer.equals("y")) {
System.out.println("Enter Number: ");
answer = sc.nextLine();
try {
Integer num1 = Integer.valueOf(answer);
if (list.isEmpty() == true) {
iList.setInner(num1); //ERROR IS HERE
list.insertFirstItem(iList);
} else {
iList = new InnerList();
iList.setInner(num1); //AND HERE
list.insertNext(iList);
}
} catch (NumberFormatException e) {
System.out.println("You must enter an number! " + e);
}
continue;
} else {
break first;
}
}
The error message is a pretty clear. You are using
iList.setInner(num1);
when you should be doing
iList.setInner(myIntegerGlist);
to match the expected argument type of the method.
I really don't understand the principle of Object Oriented Design??
So I have classes
Map class holds rooms and connects all of rooms , places all of hazards randomly into rooms, return the particulate room, and return the random rooms.
and
Player class that play turns, move player from room to another, shoot into rooms and play games.
also
Room class as follow.
import java.util.ArrayList;
public class Room
{
private int myRoomID;
private ArrayList<Room> myNeighbours;
private boolean myHasBats;
private boolean myHasPit;
private boolean myHasWumpus;
public Room(int id) {
myRoomID = id;
myNeighbours = new ArrayList<Room>();
}
public int getRoomID() {
return myRoomID;
}
public ArrayList<Room> getNeighbours() {
return myNeighbours;
}
public void connectTo(Room room) {
myNeighbours.add(room);
}
public boolean hasBats() {
return myHasBats;
}
public void setHasBats(boolean flag) {
myHasBats = flag;
}
public boolean hasPit() {
return myHasPit;
}
public void setHasPit(boolean flag) {
myHasPit = flag;
}
public boolean hasWumpus() {
return myHasWumpus;
}
public void setHasWumpus(boolean flag) {
myHasWumpus = flag;
}
public void checkBats() {
boolean bats = false;
for (Room r : myNeighbours) {
if (r.hasBats()) {
bats = true;
}
}
if (bats) {
System.out.println("I hear squeaking!");
}
}
public void checkPit() {
boolean pit = false;
for (Room r : myNeighbours) {
if (r.hasPit()) {
pit = true;
}
}
if (pit) {
System.out.println("I feel a draft!");
}
}
public void checkWumpus() {
boolean wumpus = false;
for (Room r : myNeighbours) {
if (r.hasWumpus()) {
wumpus = true;
}
}
if (wumpus) {
System.out.println("I smell a wumpus!");
}
}
public boolean enter(Player player) {
System.out.println("You are in Room " + myRoomID);
System.out.print("Exits lead to rooms");
for (Room r : myNeighbours) {
System.out.print(" " + r.getRoomID());
}
System.out.println();
checkBats();
checkPit();
checkWumpus();
if (myHasBats) {
System.out.println("A flock of bats picks you up and carries you off to another room!");
return player.moveRandom();
}
else if (myHasPit) {
System.out.println("You fall into a bottomless pit!");
return true;
}
else if (myHasWumpus) {
System.out.println("You have been eaten by a wumpus!");
return true;
}
return false;
}
public boolean shoot()
if (myHasWumpus) {
System.out.println("You killed the Wumpus!");
return true;
}
else {
System.out.println("Your arrow falls with a clatter to the floor!");
return false;
}
}
And I want to change this so that the wumpus needs to be shot more than once (you choose how many times) to be killed. Each time it is shot it runs to a random neighbouring room (not the one the player is in).
I am assuming that I need to change public boolean shoot() method into loop and call public Room getRandomRoom() as below.
But I really don't understand how to do this, especially because the use of boolean method is very confusing to me.
Does anyone know where I can find a information to learn the basic's of Object Oriented Design?
public Room getRandomRoom() {
Random rng = new Random();
int i = rng.nextInt(Map.NUM_ROOMS);
return myRooms.get(i);
}
Later on we are going to use implements in the class to separate all of hazards into classes. but for not they are all in Map and Room class.
Well without a wumpus class that's going to be messy and limited and even more inefficient. Your problem isn't that you don't get OO, it's that you are being restricted from using it.
Without out the class.
You are goingto have to add a myWumpusShotCount to room
Then in your shoot function, add 1 to it, test to see if it's 3 and if so kill it else random choose a room and set hasWumpus and WumpusShotCount in it
If you had a wumpus class it would have a property room , and another for how many bullets it had shipped and a behaviour when shot, ie the state of the wumpus and the behaviours of wumpus would be implemented by wumpus, not room. That's OO.
With the help of Tony Hopkinson, I have come up with this code but it doesn't compile yet. It says can not find symbol - method getRandomRoom() To call the methodgetRandomRoom();` from Map class.
To send wumpus to the room another room randomly
public boolean shoot() {
if (myHasWumpus) {
myWumpusShotCount = 3;
for(int i = 0; i< myWumpusShotCount; i++){
if(myWumpusShotCount<=i){
System.out.println("You killed the Wumpus!");
return true;
}
else {
Room wRoom = getRandomRoom();
System.out.println("You killed the Wumpus!");
return false;
myWumpusShotCount++;
}
System.out.println("Your arrow falls with a clatter to the floor!");
return false;
}
System.out.println("You killed the Wumpus!");
return true;
}
}
System.out.println("Your arrow falls with a clatter to the floor!");
return false;
}