Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Page 2 of 3 FirstFirst 123 LastLast
Results 26 to 50 of 54

Thread: Splitting up main method / class

  1. #26
    Forum VIP
    Join Date
    Jul 2010
    Posts
    1,676
    Thanks
    25
    Thanked 329 Times in 305 Posts

    Default Re: Splitting up main method / class

    This seem's alright, though I'm not too sure how they will be set up, how the count's will be tracked. I'm guessing that pigCount will = 0 and be incremented by every creation of Pig.
    Yep.

    So we'll put the exit option into version 2 as well? cool cool....
    We could. Or we could do it this step. It won't be hard to implement once you understand everything.
    I'm thinking about the createAnimal and promptUser at the moment. So the prompt user would ask what type of animal they wanted to create...... Would this then lead to an if elseif statement? Or a switch?
    The createAnimal() method should accept the animal the user wants as the parameter in the method. When this method is called, we are assuming that the desired animal has already been read by the user. In this method is where we would put our if-else statement, or our switch statement. We can use either, since switch statements now support Strings, but I would recommend if-else statements, since we can make it so we don't have to worry about case sensitivity (if the P in "pig" is capitalized or not). We should not have the scanner in the createAnimal() method. That method should just determine which animal to create, and create it. At the moment, we are not doing anything with the animal we create (apart from getting the sound it makes), but we will put it in an array or list later on.
    The createAnimal() method should do a few things:
    1. Determine which type of animal the "animal" String parameter represents. We would do this by: if(animal.equalsIgnoreCase("pig")) {...} else if(animal.equalsIgnoreCase("cow")) {...} ect.
    2. Create the animal
    3. Print out the sound the animal makes

    We have two options for the promptUser() method:
    Option 1:
    We prompt the user AND use the Scanner to get the input, and then pass that input to the createAnimal() method.
    Option 2:
    We can prompt the user, and scan the user's input in the main later on, and then pass the user's input to the createAnimal() method.

    Tell me which option you would like. It is really just a matter of opinion.
    The createAnimal() method can have a void return type. Depending on which option you want for the promptUser() method, we may need to return a boolean from the promptUser() method. The boolean would be false if the user wants to end the program, and true if the user wants to continue the program (we can handle this in more detail later).

    ok, so the constructor for the pig can contain the sound because that's not going to change like the count. so It's be pigClass(String "oink") ?
    Actually, I was wrong. The constructor will not need any parameters. The pig sound will always be the same for every pig, so we can make it a constant in the pig class. We can do the same for all the other animals. In fact, we can do this without even using an instance variable in the class, but we will do that in Version 2.
    NOTE TO NEW PEOPLE LOOKING FOR HELP ON FORUM:

    When asking for help, please follow these guidelines to receive better and more prompt help:
    1. Put your code in Java Tags. To do this, put [highlight=java] before your code and [/highlight] after your code.
    2. Give full details of errors and provide us with as much information about the situation as possible.
    3. Give us an example of what the output should look like when done correctly.

    Join the Airline Management Simulation Game to manage your own airline against other users in a virtual recreation of the United States Airline Industry. For more details, visit: http://airlinegame.orgfree.com/

  2. #27
    Member
    Join Date
    Dec 2013
    Posts
    51
    Thanks
    11
    Thanked 0 Times in 0 Posts

    Default Re: Splitting up main method / class

    Quote Originally Posted by aussiemcgr View Post
    Tell me which option you would like. It is really just a matter of opinion
    I think the version where the Scanner is integrated into the class and rather than the main method seem's more 'proper' for some reason? I really don't know though.



    Quote Originally Posted by aussiemcgr View Post
    The createAnimal() method should accept the animal the user wants as the parameter in the method. When this method is called, we are assuming that the desired animal has already been read by the user
    OK, so I've put that into my createAnimal(String Animal) method.... And I've put the scanner before that method, though I'm not sure if that's where the scanner should be or not.

    here's the code that I've tried for the FarmClass :

    import java.util.Scanner;
     
    public class FarmClass {
     
    	int pigCount;
    	int cowCount;
    	int sheepCount;
     
     
     
     
    	//Prompt user method
     
    	public String promptUser() {
    		System.out.println("what kind of animal would you like to create?");
    		Scanner scan = new Scanner(System.in);
     
    		String animal = scan.nextLine();
     
    		return animal;
    	}
     
     
    	// Not sure if this scanner's in the right place... It should be in this
    	// class though?
     
     
     
    	// create animal method
     
    	public void createAnimal(String animal) {
     
    		if (animal.equalsIgnoreCase("cow")) {
     
    			cowCount++;
     
    			// Not sure what I'm doing here... I'm trying to think of a way to
    			// add the cow count to the newly created cow, but I can't really
    			// work it. Also, I'm not sure If I'm meant to create the cow in
    			// this section, or how I'm meant to go about creating it.
    			Animal newCow = new cow[cowCount];
    			String sound = "moo";
     
    		}
     
    		else if (animal.equalsIgnoreCase("pig")) {
    			pigCount++;
     
     
    			String sound = "oink";
     
     
    		}
     
    		else if (animal.equalsIgnoreCase("sheep")) {
     
    			sheepCount++;
     
    			String sound = "baaa";
    		}
     
     
    	}
     
    }


    Not sure if any of that's in the right ball park.... There should be some fairly obvious mistakes in there though. I'm unsure about creating a new animal from the createAnimal method of the FarmClass... I'm not really sure about the scanner either and how that's going to work...

    cheers

  3. #28
    Forum VIP
    Join Date
    Jul 2010
    Posts
    1,676
    Thanks
    25
    Thanked 329 Times in 305 Posts

    Default Re: Splitting up main method / class

    Ok, the promptUser() method looks good.

    I will give you some additional help with the createAnimal() method.
    Your if-else statements are correct.
    For the cow if statement, you would say something like this:
    if (animal.equalsIgnoreCase("cow")) {
    	cowCount++;
    	Cow newCow = new Cow();
    	System.out.println("The Cow says "+newCow.getSound());
    }
    The Cow class should contain a String instance variable called "sound", and a getSound() method, which just returns the sound variable. In the Cow class, you should set the sound variable to: "moo"
    Try to repeat that same behavior for the pig and the sheep. You will need to have the Cow, Pig, and Sheep classes for everything to compile. Don't worry about the Animal class, we will do that in Step 2.
    NOTE TO NEW PEOPLE LOOKING FOR HELP ON FORUM:

    When asking for help, please follow these guidelines to receive better and more prompt help:
    1. Put your code in Java Tags. To do this, put [highlight=java] before your code and [/highlight] after your code.
    2. Give full details of errors and provide us with as much information about the situation as possible.
    3. Give us an example of what the output should look like when done correctly.

    Join the Airline Management Simulation Game to manage your own airline against other users in a virtual recreation of the United States Airline Industry. For more details, visit: http://airlinegame.orgfree.com/

  4. The Following User Says Thank You to aussiemcgr For This Useful Post:

    Scren (February 1st, 2014)

  5. #29
    Member
    Join Date
    Dec 2013
    Posts
    51
    Thanks
    11
    Thanked 0 Times in 0 Posts

    Default Re: Splitting up main method / class

    I'll have a bash at creating the other classes now.... I'll post back when I'm done!

    --- Update ---

    Ok I've made those...

    I'm still kind of waiting for the dot's to join up around the scanner usage, the counting and the calling between classes, but I think it's there! Onto the main method?

    Farm Class :
    import java.util.Scanner;
     
    public class FarmClass {
     
    	int pigCount;
    	int cowCount;
    	int sheepCount;
     
    	// Prompt user method
     
    	public String promptUser() {
    		System.out.println("what kind of animal would you like to create?");
    		Scanner scan = new Scanner(System.in);
     
    		String animal = scan.nextLine();
     
    		return animal;
    	}
     
    	public void createAnimal(String animal) {
     
    		if (animal.equalsIgnoreCase("cow")) {
     
    			cowCount++;
    			Cow newCow = new Cow();
    			System.out.println("The cow say's " + newCow.getSound());
    		}
     
    		else if (animal.equalsIgnoreCase("pig")) {
    			pigCount++;
    			Pig newPig = new Pig();
    			System.out.println("The pig goes " + newPig.getSound());
    		}
     
    		else if (animal.equalsIgnoreCase("sheep")) {
     
    			sheepCount++;
    			Sheep newSheep = new Sheep();
    			System.out.println("The sheep says " + newSheep.getSound());
     
    		}
     
    	}
     
    }

    Cow:
    public class Cow {
     
    	public String sound = "Moo";
     
    	public String getSound() {
    		return sound;
    	}
     
    }

    Pig:
    public class Pig {
     
    	public String sound = "Oink";
     
    	public String getSound() {
    		return sound;
    	}
     
    }



    Sheep:
    public class Sheep {
     
    	public String sound = "Baaa";
     
    	public String getSound() {
    		return sound;
    	}
     
    }

  6. #30
    Forum VIP
    Join Date
    Jul 2010
    Posts
    1,676
    Thanks
    25
    Thanked 329 Times in 305 Posts

    Default Re: Splitting up main method / class

    Yep, that all looks good.
    So now you have two options:
    1. You can create another class for the main
    2. You can add it to your Farm class

    Your Farm class is your "manager" here, so your main will interact with the Farm class directly. So, your main will do the following things:
    1. Create a new Farm class instance (the same way you created new instances of the cows, pigs, sheep, ect.).
    2. Create a loop. The exit condition for your loop can either be a set number of iterations, or by adding an exit-case to your user input. We will eventually do the latter, but if you want to do the former now to simplify this step, that is fine too.
    3. In the loop, call the Farm class instance's promptUser() method, and capture the result returned by the method in some local String variable.
    4. In the loop, call the Farm class instance's createAnimal() method, and pass the result from #3 to it as the animal parameter.

    And that's all your main has to do.
    NOTE TO NEW PEOPLE LOOKING FOR HELP ON FORUM:

    When asking for help, please follow these guidelines to receive better and more prompt help:
    1. Put your code in Java Tags. To do this, put [highlight=java] before your code and [/highlight] after your code.
    2. Give full details of errors and provide us with as much information about the situation as possible.
    3. Give us an example of what the output should look like when done correctly.

    Join the Airline Management Simulation Game to manage your own airline against other users in a virtual recreation of the United States Airline Industry. For more details, visit: http://airlinegame.orgfree.com/

  7. #31
    Member
    Join Date
    Dec 2013
    Posts
    51
    Thanks
    11
    Thanked 0 Times in 0 Posts

    Default Re: Splitting up main method / class

    Will try this now - I'm creating a main method separate to the FarmClass. I thought that the scanner in the promptUser() method of the FarmClass was capturing the users input..?

    Does this mean that there should be a getAnimal(); method created in the FarmClass? I've tried to make a main method but it doesn't seem to be incrementing the count.

    I guess I'm stuck on 3 - I'm getting confused because I thought that the promptUser method was meant to do all that...

    Here's the main method that I've written so far :

     
    import java.util.Scanner;
     
     
    public class FarmMain {
     
    	public static void main(String[] args) {
     
    		FarmClass myFarm = new FarmClass();
     
     
     
    		Scanner scan = new Scanner(System.in);
     
     
    		for(int i = 0 ; i < 4; i++){
     
    			myFarm.promptUser();
     
    			/*String userAnimal = scan.nextLine();
    */			
    			System.out.println(myFarm.pigCount);
     
    		}
     
     
     
     
    	}
     
    }

    here's the return from the console after running that method;

    what kind of animal would you like to create?
    pig
    0
    what kind of animal would you like to create?

  8. #32
    Forum VIP
    Join Date
    Jul 2010
    Posts
    1,676
    Thanks
    25
    Thanked 329 Times in 305 Posts

    Default Re: Splitting up main method / class

    Ok, you are very close.

    This is what I was describing:
    for(int i = 0 ; i < 4; i++){
    	String userAnimal = myFarm.promptUser();
     
    	myFarm.createAnimal(userAnimal);
     
    	System.out.println(myFarm.pigCount);
     
    }

    Do you understand what I did here?
    NOTE TO NEW PEOPLE LOOKING FOR HELP ON FORUM:

    When asking for help, please follow these guidelines to receive better and more prompt help:
    1. Put your code in Java Tags. To do this, put [highlight=java] before your code and [/highlight] after your code.
    2. Give full details of errors and provide us with as much information about the situation as possible.
    3. Give us an example of what the output should look like when done correctly.

    Join the Airline Management Simulation Game to manage your own airline against other users in a virtual recreation of the United States Airline Industry. For more details, visit: http://airlinegame.orgfree.com/

  9. #33
    Member
    Join Date
    Dec 2013
    Posts
    51
    Thanks
    11
    Thanked 0 Times in 0 Posts

    Default Re: Splitting up main method / class

    Not really - where has the userAnimal variable come from? or is that created by invoking that method?

    Ahhhh I see you've created a String variable then passed that into myFarm.promptUser();

    OK that's cool ! What's that type of thing called? I guess you can do that with any relating method's return type? So if it were numbers you'd have int userAnimalNum = myFarm.promptUser(); ?


    now the output of the program is :

     
    what kind of animal would you like to create?
    pig
    The pig goes Oink
    1
    what kind of animal would you like to create?
    cow
    The cow say's Moo
    1
    what kind of animal would you like to create?
    sheep
    The sheep says Baaa
    1
    what kind of animal would you like to create?
    pig
    The pig goes Oink
    2

    Not sure what the next stage is... creating an array update from the counts, or the user exit?

    nice one

  10. #34
    Forum VIP
    Join Date
    Jul 2010
    Posts
    1,676
    Thanks
    25
    Thanked 329 Times in 305 Posts

    Default Re: Splitting up main method / class

    Not really - where has the userAnimal variable come from? or is that created by invoking that method?

    Ahhhh I see you've created a String variable then passed that into myFarm.promptUser();

    OK that's cool ! What's that type of thing called? I guess you can do that with any relating method's return type? So if it were numbers you'd have int userAnimalNum = myFarm.promptUser(); ?
    Ok, so look at your promptUser() method. That method returns a String. The userAnimal variable is set to whatever value is returned by the promptUser() method. We then pass that variable to your createAnimal() method.
    Yes, if promptUser returned an int, we would have: int userAnimalNum = myFarm.promptUser();

    Not sure what the next stage is... creating an array update from the counts, or the user exit?
    Ok, so for our next step, let's do both.
    We would get rid of the count variables in your Farm class, and replace them with List objects. We will use Lists instead of arrays, since Lists do not require you to specify its size. If you had an array of size 5, and you tried to add a 6th item to it, you would get an error. A List object is not constrained by size limits.

    So, how do we create a List? Well, first off, here is the List API: List (Java Platform SE 7 )
    List is an interface, meaning we cannot initialize a new List. We need to use a class which implements the List interface. The most common used class is the ArrayList class.
    List also has something called a "type parameter". The type parameter is used to say: I only want this particular type of object in this List. You have probably seen arrays initialized like this:
    Pig[] array = new Pig[5];
    That creates an array of size 5, which can ONLY contain Pig objects. By comparison, this is how we create a Pig List:
    List<Pig> pigList = new ArrayList<Pig>();
    That creates a list (of any size) which can ONLY contain Pig objects.

    Now, since we got rid of the count variables, we cannot increment the count when we create a new Pig. But that is ok, because we are going to add the new Pig to the list we created. Have a look at this code:
    Pig pig = new Pig();
    pigList.add(pig);
    System.out.println("Pig Count: "+pigList.size());
    The pigList.size() replaces our count variable. The size() method returns the number of Pigs in the List, which is the count.

    Tell me how much of that makes sense. If you understand it, try to implement it for the Pig, Cow, and Sheep.
    NOTE TO NEW PEOPLE LOOKING FOR HELP ON FORUM:

    When asking for help, please follow these guidelines to receive better and more prompt help:
    1. Put your code in Java Tags. To do this, put [highlight=java] before your code and [/highlight] after your code.
    2. Give full details of errors and provide us with as much information about the situation as possible.
    3. Give us an example of what the output should look like when done correctly.

    Join the Airline Management Simulation Game to manage your own airline against other users in a virtual recreation of the United States Airline Industry. For more details, visit: http://airlinegame.orgfree.com/

  11. The Following User Says Thank You to aussiemcgr For This Useful Post:

    Scren (February 1st, 2014)

  12. #35
    Member
    Join Date
    Dec 2013
    Posts
    51
    Thanks
    11
    Thanked 0 Times in 0 Posts

    Default Re: Splitting up main method / class

    Just looking at this... going to have a bash. I think that I'm removing all the count int's and replacing them with this <list> interface. Going to try that now.

    --- Update ---

    Cool that's worked nicely, I'm trying to do a get out loop at the moment but I'm not sure how's best, I've been trying a while with a scanner input, but I don't really get where to put it... I've I nest the for loop into the while loop it doesn't seem to work, and If I have the while loop in the for loop then it's not really doing anything....

    It would be ideal If I could access the promptUser scanner, but because that's made within the other class I can't get to it....

    I've been trying if statement but I'm having the same problem, it either skips the for loop or it doesn't do anything.

    here's the (not working) code at the moment though :


    import java.util.Scanner;
     
    public class FarmMain {
     
    	public static void main(String[] args) {
     
    		FarmClass myFarm = new FarmClass();
     
    		Scanner scan = new Scanner(System.in);
     
    		String makeMore = null;
    		String end = "Y";
     
    		if (makeMore.equalsIgnoreCase(end)){
     
    			for (int i = 0; i < 4; i++) {
     
    				String userAnimal = myFarm.promptUser();
    				myFarm.createAnimal(userAnimal);
     
    				System.out.println("Would you like to make more animals? Y/N");
     
    				String makeMoreAnswer = scan.nextLine();
    				makeMore = makeMoreAnswer;
    				}
     
    			break;
     
    		}
     
    		System.out.println("\nAnimals created!");
     
    		myFarm.getAnimalTotals();
     
    	}
     
    }

    and here's the FarmClass now :

    import java.util.ArrayList;
    import java.util.List;
    import java.util.Scanner;
     
    public class FarmClass {
     
    	List pigList = new ArrayList<Pig>();
    	List cowList = new ArrayList<Cow>();
    	List sheepList = new ArrayList<Sheep>();
     
    	public String promptUser() {
    		System.out.println("what kind of animal would you like to create?");
    		Scanner scan = new Scanner(System.in);
     
    		String animal = scan.nextLine();
     
    		return animal;
    	}
     
    	public void createAnimal(String animal) {
     
    		if (animal.equalsIgnoreCase("cow")) {
     
    			Cow cow = new Cow();
    			cowList.add(cow);
    			System.out.println("Cow count : " + cowList.size());
    			System.out.println("The cow say's " + cow.getSound());
    		}
     
    		else if (animal.equalsIgnoreCase("pig")) {
    			Pig pig = new Pig();
    			pigList.add(pig);
    			System.out.println("Pig count : " + pigList.size());
    			System.out.println("The pig goes " + pig.getSound());
    		}
     
    		else if (animal.equalsIgnoreCase("sheep")) {
     
    			Sheep sheep = new Sheep();
    			sheepList.add(sheep);
    			System.out.println("Sheep count : " + sheepList.size());
    			System.out.println("The sheep says " + sheep.getSound());
     
    		}
     
    	}
     
    	public void getAnimalTotals() {
    		System.out.println("\nCow count : " + cowList.size()
    				+ "\nSheep count : " + sheepList.size() + "\nPig count : "
    				+ pigList.size());
    	}
     
    }


    --- Update ---

    I'm knackered again, I'll have time tomorrow for this though. cheers!

  13. #36
    Forum VIP
    Join Date
    Jul 2010
    Posts
    1,676
    Thanks
    25
    Thanked 329 Times in 305 Posts

    Default Re: Splitting up main method / class

    Ok, you have the right idea. Your List is correct, but I would recommend one change: include the list data type on both ends.
    So, instead of this:
    List pigList = new ArrayList<Pig>();
    Do this:
    List<Pig> pigList = new ArrayList<Pig>();
    As for Java 7, you could do new ArrayList<>() instead of new ArrayList<Pig>(), but I still prefer the first way. However, it is very important to include the <Pig> in the beginning. I can give you a detailed explanation why if you would like me to, but it might be a bit too complex for you right now, and might just confuse you more.

    Now, about creating the end case. What you want to do is create a situation where you can "break" out of the loop. This needs to be done from within the loop. When a loop is ran, the operations in the parentheses of the loop and inside the loop itself are always evaluated, but conditions before the loop are not. So, this:
    if (makeMore.equalsIgnoreCase(end)){
    	for (int i = 0; i < 4; i++) {
    		...
    	}
    }
    will not work because the if statement before the loop is not reevaluated while the loop is running.

    Let's simply your design by prompting the user for the type of animal, or the exit case, at the same time.
    In your Farm class, change your prompt from:
    System.out.println("what kind of animal would you like to create?");
    to this:
    System.out.println("what kind of animal would you like to create? Or enter 'exit' to terminate the program.");
    Now, let's go back to your main from before the change:
    for(int i = 0 ; i < 4; i++){
    	String userAnimal = myFarm.promptUser();
    	myFarm.createAnimal(userAnimal);
    	System.out.println(myFarm.pigCount);
    }
    So, with the new promptUser() method, if the user wants to exit the program, they will enter the word: exit instead of an animal name.
    So, we need to include an if statement in the while loop, which breaks the loop if the user replied with: exit. I added comments to describe the change that needs to occur:
    for(int i = 0 ; i < 4; i++){
    	String userAnimal = myFarm.promptUser();
     
    	// check if userAnimal equals "exit" here
    	// if userAnimal does equal "exit", put your break statement here	
     
    	myFarm.createAnimal(userAnimal);
    	System.out.println(myFarm.pigCount);
    }

    Does that make sense?
    NOTE TO NEW PEOPLE LOOKING FOR HELP ON FORUM:

    When asking for help, please follow these guidelines to receive better and more prompt help:
    1. Put your code in Java Tags. To do this, put [highlight=java] before your code and [/highlight] after your code.
    2. Give full details of errors and provide us with as much information about the situation as possible.
    3. Give us an example of what the output should look like when done correctly.

    Join the Airline Management Simulation Game to manage your own airline against other users in a virtual recreation of the United States Airline Industry. For more details, visit: http://airlinegame.orgfree.com/

  14. The Following User Says Thank You to aussiemcgr For This Useful Post:

    Scren (February 3rd, 2014)

  15. #37
    Member
    Join Date
    Dec 2013
    Posts
    51
    Thanks
    11
    Thanked 0 Times in 0 Posts

    Default Re: Splitting up main method / class

    I don't really see how the nested if statement can break out of the for loop? Because it's nested won't it just break out of the if statement back into the for loop etc...?

    OK wow I just tried it and it worked I didn't think that would work (for reasons above!)

    Here's the amended code :

    Farm Main


    • Added the if statement with the break

    • changed the for loop to an infinite one


    • Added some basic validation, It's kind of do-able for a list this size but if there were 20 animal's in the farm I imagine the the method I've used here would be a bit of a chore, or just not an option


    import java.util.Scanner;
     
    public class FarmMain {
     
    	public static void main(String[] args) {
     
    		FarmClass myFarm = new FarmClass();
     
    		Scanner scan = new Scanner(System.in);
     
    		String makeMore = null;
    		String end = "Y";
     
    			for (;;) {
     
    				String userAnimal = myFarm.promptUser();
    				myFarm.createAnimal(userAnimal);
     
     
    				if(!userAnimal.equalsIgnoreCase("cow") && (!userAnimal.equalsIgnoreCase("pig") && (!userAnimal.equalsIgnoreCase("Sheep")))){
    					System.out.println("Sorry! we don't have any of those\n");
     
    				}
     
     
    				if(userAnimal.equalsIgnoreCase("exit")){
    					break;
    				}
     
    				}
     
     
    		System.out.println("\nAnimals created!");
     
    		myFarm.getAnimalTotals();
     
    	}
     
    }

    here's the FarmClass just in case some of those references aren't expected ;

    FarmClass

    import java.util.ArrayList;
    import java.util.List;
    import java.util.Scanner;
     
    public class FarmClass {
     
    	List<Pig> pigList = new ArrayList<Pig>();
    	List<Cow> cowList = new ArrayList<Cow>();
    	List<Sheep> sheepList = new ArrayList<Sheep>();
     
    	public String promptUser() {
    		System.out.println("what kind of animal would you like to create? Or enter 'exit' to terminate the program");
    		Scanner scan = new Scanner(System.in);
     
    		String animal = scan.nextLine();
     
    		return animal;
    	}
     
    	public void createAnimal(String animal) {
     
    		if (animal.equalsIgnoreCase("cow")) {
     
    			Cow cow = new Cow();
    			cowList.add(cow);
    			System.out.println("Cow count : " + cowList.size());
    			System.out.println("The cow say's " + cow.getSound());
    		}
     
    		else if (animal.equalsIgnoreCase("pig")) {
    			Pig pig = new Pig();
    			pigList.add(pig);
    			System.out.println("Pig count : " + pigList.size());
    			System.out.println("The pig goes " + pig.getSound());
    		}
     
    		else if (animal.equalsIgnoreCase("sheep")) {
     
    			Sheep sheep = new Sheep();
    			sheepList.add(sheep);
    			System.out.println("Sheep count : " + sheepList.size());
    			System.out.println("The sheep says " + sheep.getSound());
     
    		}
     
    	}
     
    	public void getAnimalTotals() {
    		System.out.println("\nCow count : " + cowList.size()
    				+ "\nSheep count : " + sheepList.size() + "\nPig count : "
    				+ pigList.size());
    	}
     
    }

  16. #38
    Forum VIP
    Join Date
    Jul 2010
    Posts
    1,676
    Thanks
    25
    Thanked 329 Times in 305 Posts

    Default Re: Splitting up main method / class

    I don't really see how the nested if statement can break out of the for loop? Because it's nested won't it just break out of the if statement back into the for loop etc...?

    OK wow I just tried it and it worked I didn't think that would work (for reasons above!)
    A break statement breaks loops, not if-else statements.
    However, for future reference, you can break out of nested loops by labeling the loop. Here is an example of breaking out of a nested loop:
    OUTER:
    for(int i=0;i<10;i++) {
    	for(int x=0;x<5;x++) {
    		if(x==2) {
    			break OUTER;
    		}
    	}
    }
    In the above code, I labeled the outer loop: OUTER, and specified the loop I wanted to break out of after the break statement. That is just a handy thing to keep in your head.

    This code:
    if(!userAnimal.equalsIgnoreCase("cow") && (!userAnimal.equalsIgnoreCase("pig") && (!userAnimal.equalsIgnoreCase("Sheep")))){
    	System.out.println("Sorry! we don't have any of those\n");
    }
    should be added to your FarmClass's createAnimal() method. It can be just an else statement at the end. The reason for this is to reduce computations. If the user input is neither of those things, you will have checked the values twice: once in the createAnimal() method, and a second time to evaluate that if statement. Part of programming is finding ways to reduce computations so the program is less complex and faster.

    for (;;)
    This should be changed to this:
    while(true)

    if(userAnimal.equalsIgnoreCase("exit")){
    	break;
    }
    Evaluate this before you make the call to farm.createAnimal(). We want to break before attempting to create an animal.


    Ok, so the next step will be creating an abstract Animal class. But, before we do that, we need to add an extra method to our Pig, Cow, and Sheep classes. In each class, add a method: getName().
    The method should just return the name of the animal, so Pig would return "Pig", Cow would return "Cow", and Sheep would return "Sheep".
    After you do that, go back to your FarmClass, and in the createAnimal() method, change the print statements to include the call to the animal's getName() method. For example, change this:
    System.out.println("Pig count : " + pigList.size());
    System.out.println("The pig goes " + pig.getSound());
    To this:
    System.out.println(pig.getName()+" count : " + pigList.size());
    System.out.println("The "+pig.getName()+" goes " + pig.getSound());


    After you get that done, we will start the next step. For future reference, our next step will cover a few things:
    1. We will create the abstract Animal class, which all the animal types will extend from (we can create an abstract class or an interface, it is up to you)
    2. We will simplify the FarmClass to take advantage of the new Animal class
    3. We will create a new way to count the number of each animal. We can do this with simple methods, or I can introduce you to Maps. It is up to you.
    NOTE TO NEW PEOPLE LOOKING FOR HELP ON FORUM:

    When asking for help, please follow these guidelines to receive better and more prompt help:
    1. Put your code in Java Tags. To do this, put [highlight=java] before your code and [/highlight] after your code.
    2. Give full details of errors and provide us with as much information about the situation as possible.
    3. Give us an example of what the output should look like when done correctly.

    Join the Airline Management Simulation Game to manage your own airline against other users in a virtual recreation of the United States Airline Industry. For more details, visit: http://airlinegame.orgfree.com/

  17. #39
    Member
    Join Date
    Dec 2013
    Posts
    51
    Thanks
    11
    Thanked 0 Times in 0 Posts

    Default Re: Splitting up main method / class

    It can be just an else statement at the end. The reason for this is to reduce computations. If the user input is neither of those things
    Ah of course, that'll be the easier way to do that! Although typing exit

    In the above code, I labeled the outer loop: OUTER, and specified the loop I wanted to break out of after the break statement. That is just a handy thing to keep in your head
    Yes - I've seen this before with a continue statement, completely forgot about it... handy

    for (;;)
    This should be changed to this:
    while(true)
    Ok cool - it looks neater like that... makes sense!


    I've amended the classes now, here's what the classes looks like ;

    FarmMain

    import java.util.Scanner;
     
    public class FarmMain {
     
    	public static void main(String[] args) {
     
    		FarmClass myFarm = new FarmClass();
     
    		Scanner scan = new Scanner(System.in);
     
    		String makeMore;
    		String end = "Y";
     
    		for (;;) {
     
    			String userAnimal = myFarm.promptUser();
     
     
     
    			if (userAnimal.equalsIgnoreCase("exit")) {
    				break;
    			}
     
    			myFarm.createAnimal(userAnimal);
    		}
     
    		System.out.println("\nAnimals created!");
     
    		myFarm.getAnimalTotals();
     
    	}
     
    }
    FarmClass

    import java.util.ArrayList;
    import java.util.List;
    import java.util.Scanner;
     
    public class FarmClass {
     
    	List<Pig> pigList = new ArrayList<Pig>();
    	List<Cow> cowList = new ArrayList<Cow>();
    	List<Sheep> sheepList = new ArrayList<Sheep>();
     
    	public String promptUser() {
    		System.out
    				.println("what kind of animal would you like to create? Or enter 'exit' to terminate the program");
    		Scanner scan = new Scanner(System.in);
     
    		String animal = scan.nextLine();
     
    		return animal;
    	}
     
    	public void createAnimal(String animal) {
     
    		if (animal.equalsIgnoreCase("cow")) {
     
    			Cow cow = new Cow();
    			cowList.add(cow);
    			System.out.println("The " + cow.getName() + " count : " + cowList.size());
    			System.out.println("The cow say's " + cow.getSound());
    		}
     
    		else if (animal.equalsIgnoreCase("pig")) {
    			Pig pig = new Pig();
    			pigList.add(pig);
    			System.out.println("The " + pig.getName() +" count : " + pigList.size());
    			System.out.println("The pig goes " + pig.getSound());
    		}
     
    		else if (animal.equalsIgnoreCase("sheep")) {
     
    			Sheep sheep = new Sheep();
    			sheepList.add(sheep);
    			System.out.println("The " + sheep.getName() +" count : " + sheepList.size());
    			System.out.println("The sheep says " + sheep.getSound());
    		} 
     
    		else {
    			System.out.println("Sorry! we don't have any of those\n");
    		}
     
    	}
     
    	public void getAnimalTotals() {
    		System.out.println("\nCow count : " + cowList.size()
    				+ "\nSheep count : " + sheepList.size() + "\nPig count : "
    				+ pigList.size());
    	}
     
    }

    And one of the animal classes ;

    PigClass
    public class Pig {
     
    	public String sound = "Oink\n";
     
    	public String name = "Pig";
     
    	public String getName() {
    		return name;
    	}
     
    	public String getSound() {
    		return sound;
    	}
     
    }

    We will create the abstract Animal class, which all the animal types will extend from (we can create an abstract class or an interface, it is up to you)
    I've never really used either so I'm not sure - I guess which ever you feel would either be best to learn, most applicable to this example or the one that you would use personally!

    Thanks

  18. #40
    Forum VIP
    Join Date
    Jul 2010
    Posts
    1,676
    Thanks
    25
    Thanked 329 Times in 305 Posts

    Default Re: Splitting up main method / class

    Ok, well abstract classes and interfaces are not classes which can be initialized. That means that you can not create a "new" instance of them. They require a subclass to extend (in the case of abstract) or implement (in the case of interface) them.

    An interface provides a mandatory minimum outline for its implementing subclasses. An interface contains only method declarations, but no implementation of the methods. Every class which implements the interface is required to provide an implementation to each method in the interface. An interface looks like this:
    public interface SomeInterface {
    	public void methodOne();
    	public boolean methodTwo();
    	public void methodThree(String var);
    	public int methodFour(String var);
    }
    It just contains a list of the methods, that is it. When a class implements an interface, they need to provide an implementation of EVERY method in the interface. So if we have a class which implements SomeInteface, it needs to provide some directions for each method:
    public class SomeClass implements SomeInterface {
    	@Override // This is an annotation used to tell the programmer that the method is being inherited and overridden
    	public void methodOne() {
    		System.out.println("Method One");
    	}
     
    	@Override
    	public boolean methodTwo() {
    		return true;
    	}
     
    	@Override
    	public void methodThree(String var) {
    		System.out.println("Method Three: "+var);
    	}
     
    	@Override
    	public int methodFour(String var) {
    		System.out.println("Method Four: "+var);
    		return 1;
    	}
    }

    Now, an abstract class is similar to an interface, but you have a bit more flexibility. Abstract classes can provide some method implementations, and they can include instance variables and stuff. An abstract class is essentially just a normal super class, but it cannot be initialized. However, abstract classes allow you to create abstract methods. Abstract methods are exactly like the methods in the interface. They are not provided with an implementation, and the subclass is REQUIRED to provide an implementation. This is an example of a simple abstract class:
    public abstract class SomeAbstractClass {
    	/* This variable is protected because protected variables do not 
    	 * allow outside access, but can be directly accessed by a subclass
    	 */
    	protected String text = "This is an instance variable"; 
     
    	public abstract boolean methodTwo();
    	public abstract int methodFour(String var);
     
    	public void methodOne() {
    		System.out.println("Method One: "+text);
    	}
    	public void methodThree(String var) {
    		System.out.println("Method Three: "+var);
    	}
    }
    Our subclass would then look like this:
    public class SomeClass extends SomeAbstractClass {
    	@Override // This is an annotation used to tell the programmer that the method is being inherited and overridden
    	public boolean methodTwo() {
    		System.out.println("We can access the text directly variable: "+text);
    		return true;
    	}
     
    	@Override
    	public int methodFour(String var) {
    		System.out.println("Method Four: "+var);
    		return 1;
    	}
    }
    SomeClass has all the methods implemented methods of SomeAbstractClass, as well as the abstract methods it provided implementations for.

    So, for both the interface and the abstract examples above, all of these method calls can be used for either one:
    someClass.methodOne();
    someClass.methodTwo();
    someClass.methodThree("some string");
    someClass.methodFour("some string");

    Now, there is one last little bit of information to know about interfaces and abstract classes. Abstract classes are treated like normal subclasses, in the sense that subclasses extend from them. In Java, a subclass can only extend from ONE super class. So, you can not have a class which extends two abstract classes (or extends a normal class and an abstract class). However, Java allows classes to implement as many interfaces as you want. So, a class can implement one, ten, a hundred, a thousand, ect. interfaces. A class can also extend one abstract class (or normal class) while also implementing as many interfaces as it wants.
    This is where design becomes important. If you need a class to inherit from two different outlines, at least one of them MUST be an interface (or both of them). If you need a class to inherit from a normal class AND two different outlines, you need to extend the normal class, and the two outlines MUST both be interfaces.

    Tell me if you understand all that. It is very conceptual.

    So, for your purposes, it doesn't really matter either way. Let's give it a try with an abstract class, because it will allow us to do something a bit cool, and if you can understand why what we will do works, you will have pretty much understood how abstract classes, and inheritance in general works. So before we continue, make sure you understand everything in this post. Once you do, create an abstract class named Animal, and I will tell you what to do from there.
    NOTE TO NEW PEOPLE LOOKING FOR HELP ON FORUM:

    When asking for help, please follow these guidelines to receive better and more prompt help:
    1. Put your code in Java Tags. To do this, put [highlight=java] before your code and [/highlight] after your code.
    2. Give full details of errors and provide us with as much information about the situation as possible.
    3. Give us an example of what the output should look like when done correctly.

    Join the Airline Management Simulation Game to manage your own airline against other users in a virtual recreation of the United States Airline Industry. For more details, visit: http://airlinegame.orgfree.com/

  19. The Following User Says Thank You to aussiemcgr For This Useful Post:

    Scren (February 3rd, 2014)

  20. #41
    Member
    Join Date
    Dec 2013
    Posts
    51
    Thanks
    11
    Thanked 0 Times in 0 Posts

    Default Re: Splitting up main method / class

    Ace cheers mcgr - have read through the post a couple of times...

    So an interface - contain's all of the instance variables that are going to be used in further classes, If someone was making an interface for dogs they might have

    public interface dogInterface {
                public void barkAtStrangers();
                public void weight();
                public boolean pedigree();
     
    }

    Or something of that nature.... Or maybe they would have the dog as a subclass of animal, unless their program was just about dogs....

    Then abstract class, out of the two abstract class seem's like a bit of an obvious preferences, if it's more flexible?

    But then the abstract class is (this is only my 'understanding' here....) about something abstract. So 'Animal' would be an abstract class as you can't have an animal without it being a subset of. Although perhaps someone would argue that with dog? You can't just have a 'dog', you have a border collie, or a Labrador, or a mongrel etc. So I guess in that sense 'dog' could be used as an abstract class or a subclass... maybe!

    I can't really see why an interface would be beneficial at the moment, but seeing as I've never put either into practice that's not much of a surprise. You can implement many interfaces but only one abstract class I guess that's the main reason....

    In the example of the interface that you used :

    public void methodOne() {
    		System.out.println("Method One");
    	}

    this method could be called one by using

    someObject.methodOne();

    and would return the following to the console :

    Method one

    And in interfaces you can only instantiate the methods / variables - you can't actually provide the code that they would execute.

    Is that correct?

    Tell me if you understand all that. It is very conceptual
    Well, I think that I'm happy to learn it, though I get that will come from actually using them. Already going through this example with you there have been thing's that I've read but actually using them and seeing how they work is the only way to comprehend them (so thanks again!)

    for your purposes, it doesn't really matter either way. Let's give it a try with an abstract class
    Yeah that's cool....

    Let me know if there's anything it sound's like I'm missing the point on, and if there's any reading I should do before the next part..

  21. #42
    Forum VIP
    Join Date
    Jul 2010
    Posts
    1,676
    Thanks
    25
    Thanked 329 Times in 305 Posts

    Default Re: Splitting up main method / class

    So an interface - contain's all of the instance variables that are going to be used in further classes
    Method declarations, not instance variables. Very important distinction. An interface should not have instance variables in them, only method declarations.

    So 'Animal' would be an abstract class as you can't have an animal without it being a subset of. Although perhaps someone would argue that with dog? You can't just have a 'dog', you have a border collie, or a Labrador, or a mongrel etc. So I guess in that sense 'dog' could be used as an abstract class or a subclass... maybe!
    Ok, interesting question, and this depends entirely on the desired implementation. Perhaps we can add different types of dogs to our farm later to show this.
    But in a hierarchical view, I suppose you would have something like:
    Dog extends/implements Animal, and Border Collie, Labrador, ect. extend/implement Dog.
    If you want to make it so that you MUST have a type of Dog (meaning: just a Dog object would not be enough for your desired implementation, and you MUST have the type of Dog), you would probably make Dog abstract. This means you would not be able to create just a generic Dog object, but you would still be able to use all of the Dog's "traits" to create a Border Collie, Labrador, ect.

    I can't really see why an interface would be beneficial at the moment, but seeing as I've never put either into practice that's not much of a surprise. You can implement many interfaces but only one abstract class I guess that's the main reason....
    I suppose you could think of an interface as being a more abstract version of an abstract class. With an abstract class, you at least have some implementation here and there, but with an interface, you are providing no implementation. This would mean that you are expecting the interface to be so abstract that there is no logical reason to attempt to implement any of its features. In that sense, perhaps Animal should be an interface, but we won't for this example.
    If we had something like an Organism class, that would most likely be an interface. An Organism could be an animal, plant, fungus, ect. It is such a broad "idea" that there would be no point in attempting to provide an implementation for anything, since each subset would probably just have to override every method for their own purposes anyway.

    Ok, so back to the farm. We are going to create an abstract Animal class. We will do this in two steps.
    In this first step, we will make the methods abstract. So, our Pig, Sheep, and Cow all have two methods in common:
    1. getSound()
    2. getName()

    So, we can declare all of these in our abstract Animal class. So create your abstract Animal class and create the abstract method declarations for getSound() and getName().
    Then, make your Pig, Sheep, and Cow classes extend from your abstract Animal class. That is all you will need to do for this step. You could add the @Override annotations, but they are not mandatory.
    When you have that done, post all the Animal class, Pig class, Sheep class, and Cow class so I can see them.
    NOTE TO NEW PEOPLE LOOKING FOR HELP ON FORUM:

    When asking for help, please follow these guidelines to receive better and more prompt help:
    1. Put your code in Java Tags. To do this, put [highlight=java] before your code and [/highlight] after your code.
    2. Give full details of errors and provide us with as much information about the situation as possible.
    3. Give us an example of what the output should look like when done correctly.

    Join the Airline Management Simulation Game to manage your own airline against other users in a virtual recreation of the United States Airline Industry. For more details, visit: http://airlinegame.orgfree.com/

  22. #43
    Member
    Join Date
    Dec 2013
    Posts
    51
    Thanks
    11
    Thanked 0 Times in 0 Posts

    Default Re: Splitting up main method / class

    Ace, well here's the Animal class (I used Eclipse to generate the getters.... not sure if this is a not-to-do...):

    public abstract class Animal {
     
    	public String sound;
    	public String name;
     
    	public String getSound() {
    		return sound;
    	}
     
    	public String getName() {
    		return name;
    	}
     
    }

    Pig
    public class Pig extends Animal {
     
    	public String sound = "Oink\n";
     
    	public String name = "Pig";
     
    	public String getName() {
    		return name;
    	}
     
    	public String getSound() {
    		return sound;
    	}
     
    }

    Sheep
    public class Sheep extends Animal {
     
    	public String sound = "Baaa\n";
     
    	public String name = "Sheep";
     
     
    	public String getName(){
    		return name;
    	}
     
    	public String getSound() {
    		return sound;
    	}
     
    }

    Cow
    public class Cow extends Animal {
     
    	public String sound = "Moo\n";
     
    	public String name = "Cow";
     
     
    	public String getName(){
    		return name;
    	}
     
    	public String getSound() {
    		return sound;
    	}
     
    }


    Haven't made any changes to the main method or FarmClass...


    Dog extends/implements Animal, and Border Collie, Labrador, ect. extend/implement Dog.
    If you want to make it so that you MUST have a type of Dog (meaning: just a Dog object would not be enough for your desired implementation, and you MUST have the type of Dog), you would probably make Dog abstract. This means you would not be able to create just a generic Dog object, but you would still be able to use all of the Dog's "traits" to create a Border Collie, Labrador, ect
    I'm not really fully following along with this, it kind of makes sense but it's not pictured in my head. But as this is the design element I guess it's a matter of doing a bit of wax on wax off for it to sink in.


    With an abstract class, you at least have some implementation here and there
    So you can implement an abstract class say, if there was an abstract class called someAbstract. You could have ?:

    someAbstract myAbstract = new someAbstract();

    And that would work, but if it was an interface it wouldn't. Interfaces don't have any parenthesis so they can't receive any input (Not sure if that's correct or not) thy can only declare methods not variables.

  23. #44
    Forum VIP
    Join Date
    Jul 2010
    Posts
    1,676
    Thanks
    25
    Thanked 329 Times in 305 Posts

    Default Re: Splitting up main method / class

    I used Eclipse to generate the getters.... not sure if this is a not-to-do...
    That is usually fine, but not for this exact situation.

    For this Step, we want the methods to be abstract and we don't need the variables.
    So instead of this:
    public abstract class Animal {
     
    	public String sound;
    	public String name;
     
    	public String getSound() {
    		return sound;
    	}
     
    	public String getName() {
    		return name;
    	}
     
    }
    We just need the method declarations:
    public abstract class Animal {
    	public abstract String getSound();
    	public abstract String getName();
    }
    We will do the other way in the second step, but I will need to spend some time explaining why what you had doesn't work properly due to scope and variable hiding.

    This is not allowed:
    someAbstract myAbstract = new someAbstract();
    You cannot create a "new" instance of an abstract class or an interface.

    But, now we are going to do something similar (fix the previous part before doing this or it will not work properly). We are going to modify your FarmClass to use our abstract Animal class. We will do a handful of things for this step (all of this is done in the Farm class):
    1. Get rid of your Pig, Cow, and Sheep list and create a single Animal list
    2. Create 3 methods: getPigCount(), getCowCount(), and getSheepCount(). These methods will return an int, representing the number of each animal. These methods should loop through the Animal list and check each item. When you pull an item out of the Animal list (with the List.get(int index) method), you will have a generic Animal object. Now, we know that the object is not really a generic Animal object. In reality, it is either a Pig, a Cow, or a Sheep. But we don't know which one. There are two ways we can check:
    a) using the getName() method which we already have in the animal
    b) determining the class using: animal instanceof Pig
    Consider your options, read up on them a bit if you need to, and choose one.
    3. Change your createAnimal() method. To do this, we will follow these steps:
    a) create a variable before the if statements:
    public void createAnimal(String animal) {
     
    	Animal tempAnimal = null;
     
    	if (animal.equalsIgnoreCase("cow")) {
    ...
    b) Then, in the if statement, we will assign the animal variable based on the if statement instead of a local variable in the if statement, and get rid of the adding to the list and the print statements:
    ...
    if (animal.equalsIgnoreCase("cow")) {
    	tempAnimal = new Cow();
    }
    ...
    c) After all your if-else conditions, we want to do a generic add to the animalList and a print of the animal stuff:
    ...
    else {
    	System.out.println("Sorry! we don't have any of those\n");
    }
    animalList.add(tempAnimal);
    System.out.println("The " + tempAnimal.getName() + " say's " + tempAnimal.getSound());
    d) We want to prematurely exit the method if the final else condition is met (since we don't want to add a null to the list or attempt to print it):
    ...
    else {
    	System.out.println("Sorry! we don't have any of those\n");
    	return;
    }
    ...

    After you do all of that, we will discuss how to get the count values.
    Tell me how much of that makes sense, give it a try, and tell me if you have any issues.
    NOTE TO NEW PEOPLE LOOKING FOR HELP ON FORUM:

    When asking for help, please follow these guidelines to receive better and more prompt help:
    1. Put your code in Java Tags. To do this, put [highlight=java] before your code and [/highlight] after your code.
    2. Give full details of errors and provide us with as much information about the situation as possible.
    3. Give us an example of what the output should look like when done correctly.

    Join the Airline Management Simulation Game to manage your own airline against other users in a virtual recreation of the United States Airline Industry. For more details, visit: http://airlinegame.orgfree.com/

  24. The Following User Says Thank You to aussiemcgr For This Useful Post:

    Scren (February 3rd, 2014)

  25. #45
    Member
    Join Date
    Dec 2013
    Posts
    51
    Thanks
    11
    Thanked 0 Times in 0 Posts

    Default Re: Splitting up main method / class

    Ace... Times vanished in the UK, I should be able to read up on stuff and have a stab at this before work tomorrow though...

  26. #46
    Member
    Join Date
    Dec 2013
    Posts
    51
    Thanks
    11
    Thanked 0 Times in 0 Posts

    Default Re: Splitting up main method / class

    1. Get rid of your Pig, Cow, and Sheep list and create a single Animal list
    FarmClass
    public class FarmClass {
     
    	List<Animal> animalList = new ArrayList<Animal>();

    I've made that, but I'm struggling with everything else...

    2. Create 3 methods: getPigCount(), getCowCount(), and getSheepCount(). These methods will return an int, representing the number of each animal. These methods should loop through the Animal list and check each item. When you pull an item out of the Animal list (with the List.get(int index) method), you will have a generic Animal object. Now, we know that the object is not really a generic Animal object. In reality, it is either a Pig, a Cow, or a Sheep. But we don't know which one. There are two ways we can check
    I've tried to create these method's in the farm class, but I'm not sure how I'm meant to go through the arrayList with these methods. I've read bit's about list.add method's and stuff, it that something that should be in the main method or the prompt user section? I'm guessing that there need's to be some kind of :


     
    for (int i = 0 ; i ; i++) {
           System.out.println(animalList.get[i]);
    }


    But that's printing out, I'm not sure how to 'check' each item, or what exactly that means... Check that they're there? So, like the validation stage where it ensures that those animal's are actually available?

    When you pull an item out of the Animal list (with the List.get(int index) method), you will have a generic Animal object
    so I would use the code animalList.get(3) to return the third animal in the list. And the list would store cow's, pigs, sheep all together... so as an array it might look like
    animalArray[0] = "Sheep";
    animalArray[1] = "Pig";
    animalArray[2] = "Cow";
    animalArray[3] = "Pig";

    Obviously it's not an array in that sense... but there are stored like that?
    3. Change your createAnimal() method. To do this, we will follow these steps:
    a) create a variable before the if statements:


     
     
    public void createAnimal(String animal) {
     
    	Animal tempAnimal = null;
     
    	if (animal.equalsIgnoreCase("cow")) {
    ...
    I've tried to do that, although I'm not really joining the dots... Here's a part of my ammended create animal method though;


    public void createAnimal(String animal) {
     
    		if (animal.equalsIgnoreCase("cow")) {
     
    			Cow cow = new Cow();
    			cowList.add(cow);
    			System.out.println("The " + cow.getName() + " count : " + cowList.size());
    			System.out.println("The cow say's " + cow.getSound());
    		}


    Question about the promptUser method : In the method the variable animal is instantiated with the line

    String animal = scan.nextLine();
    This variable animal is declared within the braces of the prompt user method. We can access this variable with other methods because at the end of the promptUser() method the variable is returned with

    return animal;

    I just wanted to check my understanding on that one...

    I'm not sure how to tie in the counts with this, here're the classes in case I've done anything daft... As it stands in the FarmClass the get*Count() methods are just kind of hanging...



    FarmClass
    import java.util.ArrayList;
    import java.util.List;
    import java.util.Scanner;
     
    public class FarmClass {
     
    	List<Animal> animalList = new ArrayList<Animal>();
     
     
    	public int getPigCount();
    	public int getSheepCount();
    	public int getCowCount();
     
     
     
     
    	public String promptUser() {
    		System.out
    				.println("what kind of animal would you like to create? Or enter 'exit' to terminate the program");
    		Scanner scan = new Scanner(System.in);
     
    		String animal = scan.nextLine();
     
    		return animal;
    	}
     
    	public void createAnimal(String animal) {
     
    		Animal tempAnimal = null;
     
    		if (animal.equalsIgnoreCase("cow")) {
     
    			tempAnimal = new Cow();
     
    		}
     
    		else if (animal.equalsIgnoreCase("pig")) {
    			tempAnimal = new Pig();
     
    					}
     
    		else if (animal.equalsIgnoreCase("sheep")) {
     
    			tempAnimal = new Sheep();
    					} 
     
    		else {
    			System.out.println("Sorry! we don't have any of those\n");
    		}
     
    		animalList.add(tempAnimal);
    		System.out.println("The " + tempAnimal.getName() + " says " + tempAnimal.getSound());
    	}
     
    	/*public void getAnimalTotals() {
    		System.out.println("\nCow count : " + cowList.size()
    				+ "\nSheep count : " + sheepList.size() + "\nPig count : "
    				+ pigList.size());
    	}
    */
    }
    AnimalAbstractClass
    public abstract class Animal {
     
    	public abstract String getSound();
    	public abstract String getName();
     
    }
    FarmMain

    import java.util.Scanner;
     
    public class FarmMain {
     
    	public static void main(String[] args) {
     
    		FarmClass myFarm = new FarmClass();
     
    		Scanner scan = new Scanner(System.in);
    		while (true) {
     
    			String userAnimal = myFarm.promptUser();
     
     
     
    			if (userAnimal.equalsIgnoreCase("exit")) {
    				break;
    			}
     
    			myFarm.createAnimal(userAnimal);
    		}
     
    		System.out.println("\nAnimals created!");
     
    		//myFarm.getAnimalTotals();
     
    	}
     
    }

  27. #47
    Forum VIP
    Join Date
    Jul 2010
    Posts
    1,676
    Thanks
    25
    Thanked 329 Times in 305 Posts

    Default Re: Splitting up main method / class

    so I would use the code animalList.get(3) to return the third animal in the list.
    Actually that would get the 4th item, since indexes start at 1 (ie: the first item is index 0, the second item is index 1, the third item is index 2, ect.)

    I'm guessing that there need's to be some kind of :

    for (int i = 0 ; i ; i++) {
    System.out.println(animalList.get[i]);
    }

    But that's printing out, I'm not sure how to 'check' each item, or what exactly that means... Check that they're there? So, like the validation stage where it ensures that those animal's are actually available?
    Ok, well first of all, your for loop would be incorrect because you haven't specified the limit. It should read:
    for (int i = 0 ; i<animalList.size(); i++)
    Second, List.get() is a method, so you use parentheses instead of brackets:
    System.out.println(animalList.get(i));
    Continuing on with your question, we are not checking if the animal is there, but rather what type of animal it is. Your animalList is a List of Animal objects. This list can contain Animal objects. Your Pig, Cow, and Sheep classes extend your Animal class. When one class extends another, you say the subclass "is-a" super class. So when Pig extends Animal, Pig "is-a" Animal.
    So, since your animalList contains Animal objects, and Pig is-a Animal, then your animalList can contain Pig objects. More specifically, your animalList can contain all instances of Animal, including all classes which extend Animal.
    Now, we know that Animal is an abstract class, and we know that abstract classes cannot be initialized. This means that every item we pull out of the animalList is not "really" an Animal object, but rather an object for one of Animal's subclasses. But when you pull an item out of the animalList, you pull it out as an Animal object. The question becomes: so which subclass is it?
    This is where the difference between compile-time and runtime come into play. At compile-time (ie: when you are compiling your java program), all Java knows is that what you are pulling out of the animalList is an Animal object. We don't know what type of Animal, we just know it is an animal. At runtime, the Animal object we pull out will already know what type of Animal it is.
    So, when we pull an Animal out of the animalList, we have to pull it out as an Animal object:
    Animal animal = animalList.get(i);
    We know this is really some subclass of Animal, but we don't know which one yet.
    What we need to do is check its type. You can check an object's type with the: instanceof operator. So, if we wanted to ask the question: is animal an instance-of Pig, we would code:
    if(animal instanceof Pig)

    I've tried to do that, although I'm not really joining the dots... Here's a part of my ammended create animal method though;
    Ok, there is an important topic in Java called: polymorphism. It's a big word with a confusing definition, but it really just means that you can set an instance of an object to a variable with type of a superclass without losing any inherited behavior. That is also a confusing definition, but let me explain:
    public class A {}
    public class B extends A {}
    public class C extends B {}
    public class D extends A {}
    Let's consider the above classes. Now, let's consider the below assignments:
    A obj0 = new A(); // This is allowed for obvious reasons
    A obj1 = new B(); // This is allowed because B is-a A
    A obj2 = new C(); // This is allowed because C is-a B, and B is-a A, so C is-a A
    A obj3 = new D(); // This is allowed because D is-a A
    B obj4 = new C(): // This is allowed because C is-a B
    B obj5 = new A(); // This is NOT allowed, because A is not a B. Inheritence is one way, B is-a A, but A is not a B
    Review the above and ask me any questions you have. If you can understand these concepts, we can continue with your other questions.
    NOTE TO NEW PEOPLE LOOKING FOR HELP ON FORUM:

    When asking for help, please follow these guidelines to receive better and more prompt help:
    1. Put your code in Java Tags. To do this, put [highlight=java] before your code and [/highlight] after your code.
    2. Give full details of errors and provide us with as much information about the situation as possible.
    3. Give us an example of what the output should look like when done correctly.

    Join the Airline Management Simulation Game to manage your own airline against other users in a virtual recreation of the United States Airline Industry. For more details, visit: http://airlinegame.orgfree.com/

  28. #48
    Member
    Join Date
    Dec 2013
    Posts
    51
    Thanks
    11
    Thanked 0 Times in 0 Posts

    Default Re: Splitting up main method / class

    Actually that would get the 4th item
    Ah yeah of course...count from zero


    your for loop would be incorrect because you haven't specified the limit
    Yeah I left that blank for some reason...

    your for loop would be incorrect because you haven't specified the limit. It should read:
    for (int i = 0 ; i<animalList.size(); i++)
    Cool - I've seen these method's with Strings as well I think.

    When one class extends another, you say the subclass "is-a" super class. So when Pig extends Animal, Pig "is-a" Animal
    Yeah this makes sense It can be confusing sometimes when I read super class because I see the Animal class as the super class, but of course by extending the Parent class the PigClass becomes the animal...

    every item we pull out of the animalList is not "really" an Animal object, but rather an object for one of Animal's subclasses. But when you pull an item out of the animalList, you pull it out as an Animal object
    This is slightly confusing - so the program pulls out an object from the animal list as an Animal - as in the parent class. So say In my animal list I had :

    Pig, Sheep, Cow, Pig, Sheep

    And pulled the 3rd element : Cow. Java / my program would register this as an Animal rather than a Pig object / extension of Animal... Or would it see Pig, register Pig, but consider this as an animal because it extends animal...?

    At runtime, the Animal object we pull out will already know what type of Animal it is.
    Or is this (the above comment) what happens at runtime? Sorry, just got a bit confused around that one... maybe I need to try it a few times.

    you can set an instance of an object to a variable with type of a superclass without losing any inherited behaviour


    A obj0 = new A(); // This is allowed for obvious reasons
    A obj1 = new B(); // This is allowed because B is-a A
    A obj2 = new C(); // This is allowed because C is-a B, and B is-a A, so C is-a A
    A obj3 = new D(); // This is allowed because D is-a A
    B obj4 = new C(): // This is allowed because C is-a B
    B obj5 = new A(); // This is NOT allowed, because A is not a B. Inheritence is one way, B is-a A, but A is not a B

    I think I understand the logic with this, but what I'm not sure about is the actual.... So the First letter is the Class that is being assigned to the variable obj * , and then a new Class is created. You can create a new class from an object that's further up the parent - child class, not not further down (parent being high, child low). But you can't assign a variable to an object that a lower class than the one that you're instantiating with new....

    edit like a dog is an animal, and a labrador is an animal but a dog isn't a Labrador, because it could be a Scottish terrier.... And an animal isn't a dog, because it could be a cat...

    Hope that reads / show's whether it's ticking over

    Thanks

  29. #49
    Forum VIP
    Join Date
    Jul 2010
    Posts
    1,676
    Thanks
    25
    Thanked 329 Times in 305 Posts

    Default Re: Splitting up main method / class

    edit like a dog is an animal, and a labrador is an animal but a dog isn't a Labrador, because it could be a Scottish terrier.... And an animal isn't a dog, because it could be a cat...
    Yep. That is all correct.

    This is slightly confusing - so the program pulls out an object from the animal list as an Animal - as in the parent class. So say In my animal list I had :
    Pig, Sheep, Cow, Pig, Sheep
    And pulled the 3rd element : Cow. Java / my program would register this as an Animal rather than a Pig object / extension of Animal... Or would it see Pig, register Pig, but consider this as an animal because it extends animal...?
    ...Or is this (the above comment) what happens at runtime? Sorry, just got a bit confused around that one... maybe I need to try it a few times.
    Ok, this is where it gets a little hard for me to properly put into words.
    First, let's create the distinction between "variable" and "instance": the variable is on the left of the equals sign, the instance is on the right of the equals sign. The variable consists of two things: the "variable type" and the "variable name". When you are doing an assignment operation, the "instance type" needs to be assignable to the "variable type". You already know all of this, because your dog example above states it. In the below assignment example:
    Animal animal = animalList.get(i);
    Here is a breakdown of the keywords above:
    The "variable type" is: Animal
    The "variable name" is: animal
    The "instance" is whatever value is returned by the statement: animalList.get(i)

    Now let's talk about the difference between "compile-time" and "runtime".
    At compile time we know far less information about what is actually happening than we know at runtime. In order for the example statement to be allowed at "compile-time", the type of the "instance" needs either to be the same type as the "variable type" OR a child-type of the "variable type" (a type whose class extends the variable type's class). So, as long as the animalList.get(i) method returns an Animal type, a Pig type, a Cow type, or a Sheep type, the statement is allowed at "compile-time". Based on the documentation for the List class, since your animalList is of type Animal, the get() method will return an Animal type, so we are good. But, and here is the important part, the compiler doesn't know or care if the object returned by the get() method will be an instance of an Animal, or an instance of some subclass of Animal when the program is actually ran. All it cares about is that it is at least an Animal. And, one final little note, since animal is an Animal object, the ONLY methods we can invoke on the object will be methods which are available in the Animal class. That means that if the Pig class has an extra method that the Animal class does not, we cannot call that extra method with the animal object even if WE know the object will be a Pig, because the compiler doesn't know it.
    At "runtime", we know that the object returned by the get() method couldn't possibly be JUST an Animal object, since the Animal class is abstract (and abstract classes cannot be initialized). When the get() method returns an instance and assigns the animal variable to that instance, the REAL type of the Animal object is known. So, at "runtime", Java now knows that the object retrieved by the get() method is not just an Animal, but a Pig. So when it performs method calls on the animal variable, it knows to call the methods associated to the Pig class, not the Animal class. This little bit of information is important, because it's what makes method overrides possible.
    Let's expand on the A, B, C, D classes from earlier with a small example. Let's say those classes now look like this:
    public class A {
    	public int getValue() {
    		return 0;
    	}
    }
    public class B extends A {
    	public int getValue() {
    		return 1;
    	}
    }
    public class C extends B {
    	public int getValue() {
    		return 2;
    	}
    }
    public class D extends A {
    	public int getValue() {
    		return 3;
    	}
    }
    Now, let's initialize them like before, and print out the value of the getValue() method:
    A obj0 = new A();
    A obj1 = new B();
    A obj2 = new C();
    A obj3 = new D();
    B obj4 = new C():
    System.out.println("Value "+obj0.getValue()); // At runtime, it is known that obj0 is really an instance of A, so this prints: Value 0
    System.out.println("Value "+obj1.getValue()); // At runtime, it is known that obj1 is really an instance of B, so this prints: Value 1
    System.out.println("Value "+obj2.getValue()); // At runtime, it is known that obj2 is really an instance of C, so this prints: Value 2
    System.out.println("Value "+obj3.getValue()); // At runtime, it is known that obj3 is really an instance of D, so this prints: Value 3
    System.out.println("Value "+obj4.getValue()); // At runtime, it is known that obj4 is really an instance of C, so this prints: Value 2
    At compile-time, they are all variables of type: A. But at runtime, their real types are known, and the methods for their real types are used, instead of the methods for type: A.

    Tell me if that makes sense.
    NOTE TO NEW PEOPLE LOOKING FOR HELP ON FORUM:

    When asking for help, please follow these guidelines to receive better and more prompt help:
    1. Put your code in Java Tags. To do this, put [highlight=java] before your code and [/highlight] after your code.
    2. Give full details of errors and provide us with as much information about the situation as possible.
    3. Give us an example of what the output should look like when done correctly.

    Join the Airline Management Simulation Game to manage your own airline against other users in a virtual recreation of the United States Airline Industry. For more details, visit: http://airlinegame.orgfree.com/

  30. #50
    Member
    Join Date
    Dec 2013
    Posts
    51
    Thanks
    11
    Thanked 0 Times in 0 Posts

    Default Re: Splitting up main method / class

    the compiler doesn't know or care if the object returned by the get() method will be an instance of an Animal, or an instance of some subclass of Animal when the program is actually ran. All it cares about is that it is at least an Animal
    Right, is this in a way analogous to a folder system in a GUI? (I should probably stay away from using GUI as examples with this but it seemed to fit....) The highest most 'folder' (or parent class) that could work for the example is used by the compiler
    Animal animal = animalList.get(i);

    Within this analogy sub-folders (Sub-Classes / Child-Classes) are irrelevant to the compiler, It can sort these out after. Initially it just checks the highest level is correct, that animalList.get(i); is an Animal. An example for a higher level class might be life form, Animal might be a lower class than life form, although I'm not sure that if LifeForm was being used and Animal was an extension of LifeForm, would Pig then be an extension of Animal? (Can you have 'nested' extensions?) Perhaps I'm wobbling a bit off topic there...

    So, at "runtime", Java now knows that the object
    retrieved by the get() method is not just an Animal, but a Pig. So when it
    performs method calls on the animal variable, it knows to call the methods
    associated to the Pig class, not the Animal class
    We / The Java program will know this because we're going to use the
    if(animal instanceof Pig)

    Statement.... without this statement would it know? Or rather, this statement is just to enable us to return certain thing's based on what class / object is returned by the list....

    So at RunTime the animal is what ever sub-class was entered by the user, cow / sheep / pig... So for example say the PigClass had a method called makeBacon(), at what point could we use

    animal.makeBacon();

    I'm assuming that this is somehow wrong, because it would be a bit odd to have all the pig's, cow's and sheep to be called 'animal'.

    At compile-time, they are all variables of type: A. But at runtime, their real types are known, and the methods for their real types are used, instead of the methods for type: A.

    Tell me if that makes sense.
    It really does make sense, I think that I understand how the logic work's within the examples given and on a more general level. There are still some uncertainties about details though, such as the makeBacon() example above.

    I'm looking at the code at the moment (for the FarmClass) and at the bottom of the createAnimal method there is the :

    animalList.add(tempAnimal);
    		System.out.println("The " + tempAnimal.getName() + " says "
    				+ tempAnimal.getSound());

    section. Now, we've created a new Animal with the promptUser() method.

    String animal = scan.nextLine();

    So that's created a new String called Animal, so it's not actually created an Animal, just a String called Animal that represents the type of animal that they would like to create. Then the promptUser() method returns this String.

    So referencing the main method FarmMain we have the creation of the FarmClass with

    FarmClass myFarm = new FarmClass();

    Then we move into the while loop - which creates a String called userAnimal from the promptUser method. this means that the animal String from the promptUser method is now userAnimal.

    Then we use the userAnimal String variable in the if statement to validate and if user has entered break clause the program will end.

    However if they have entered a correct Animal (one that we have) into the userAnimal String the program will move onto the createAnimal method. I'm a little unsure here actually with how the variable userAnimal and promptUser animal is being passed around.

    In the main method the userAnimal is created from the promptUser method - so the animal String variable from promptUser is replaced by the user defined userAnimal.... But in the FarmClass our createAnimal method has an input of String Animal - this input is the animal variable from the promptUser class, that is now the userAnimal.

    So - the animal variable still exists within the FarmClass - but it's value has been replaced by the value input by the user. This happens before the code from the createAnimal method is processed, so by the time the process get's to createAnimal the variable animal is the animal that was input by the user. We can use the animal variable in the createAnimal class because it's returned by it's method.

    So now we're in the createAnimal class, the user having specified which they'd like to create. We create a tempAnimal and assign it's value to null. This is because we've already used the variable animal in the class (as input) so need to have another variable that can be used within the createAnimal class. Although tempAnimal is of type Animal where as animal is a String - so hmm. So what is tempAnimal at the stage of
    Animal tempAnimal = null;

    It's value is null - but is it an 'animal' ? Has this in some way declared an abstract class? I know it's not with the 'new' operator, but still. So at this point is tempAnimal an Animal, and because it's abstract its value is null?

    Anyway, tempAnimal is then assigned to the relevant object depending on the String input by the user in the promptUser method.


    After this has been assigned (or custom error returned) we use
    animalList.add(tempAnimal);

    to add this newly created animal to our list....

    So tempAnimal is added to the list, but because it's either a sheep, cow or pig, these are what value the list will return if say
    animalList.get(0);

    is used... So does Java convert them as it's putting them into the list or as it's pulling them out? (Does that even matter?) I'm just curious as to whether the list is

    animalList[0] = tempAnimal
    animalList[1] = tempAnimal
    animalList[2] = tempAnimal
    animalList[3] = tempAnimal

    and then when we call animalList.get(3) java pulls tempAnimal, knows that it's a sheep and presents it to us as a sheep. Or if it converts them on the way in and the list would look like

    animalList(0) = pig
    animalList(1) = sheep
    animalList(2) = cow
    animalList(3) = pig

    I'm pretty sure that the nomenclatures wrong there - but I hope the point translates... If it's irrelevent then fair enough!

    So that's where I think I'm at, I think that the concept of not being able to create an animal from a dog, but dog from an animal makes sense. Hopefully I've explained myself well enough to highlight any confusions though. Sorry it's a bit of an essay

Page 2 of 3 FirstFirst 123 LastLast

Similar Threads

  1. Replies: 2
    Last Post: November 18th, 2012, 02:09 PM
  2. create a test class (main method) to start(run) the class in Java
    By curious725 in forum Java Theory & Questions
    Replies: 5
    Last Post: August 1st, 2012, 03:21 AM
  3. Main method/ class problem. I can't run any script!
    By BokBok in forum What's Wrong With My Code?
    Replies: 3
    Last Post: June 28th, 2012, 05:14 PM
  4. Paint program adding classes to main method class
    By Maxfmc in forum What's Wrong With My Code?
    Replies: 0
    Last Post: April 15th, 2011, 07:01 PM
  5. Creating a scaleUp main method in a new class
    By Brainz in forum What's Wrong With My Code?
    Replies: 1
    Last Post: November 16th, 2010, 08:58 AM