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 1 of 3 123 LastLast
Results 1 to 25 of 54

Thread: Splitting up main method / class

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

    Default Splitting up main method / class

    I've written a program just for the sake of it (to learn) and it seem's like theres quite a lot in the main method that perhaps could be split up into seperate classes. I'm not too sure where should start with this though, or what my thought process should have been as I was writing the program.

    It works, though if there's anything that's a bit iffy or against general practice then it'd be nice to hear!

    import java.util.Scanner;
     
    public class Loops {
     
    	public static void main(String[] args) {
     
    		int answer = 16;
     
    		Scanner scan = new Scanner(System.in);
     
    		// Question
     
    		System.out.println("What is 4 x 4 ?\n");
     
    		// Initialises answer variable and scans console for user response
     
    		int userAnswerInt = 0;
    		userAnswerInt = scan.nextInt();
     
    		// If statement that gives correct if answers right, to over user a loop
    		// to re try if incorrect
     
    		if (userAnswerInt == answer) {
    			System.out.println("correct");
    		} else {
     
    			// Answer for getting the question incorrect
     
    			System.out.println("Incorrect\n");
    			String userContinue = null;
     
    			// Question to user
     
    			System.out.println("Would you like to continue? Y/N \n");
     
    			// I've done this because I've read that there are problems using
    			// the next int method, though I don't really understand them,
    			// something to do with a blank string!
    			String dummy = scan.nextLine();
     
    			// Should scan the console for answer to continue question
    			userContinue = scan.nextLine();
     
    			// answer required to continue
    			String continueAnswer = "y";
    			if (userContinue.equalsIgnoreCase(continueAnswer)) {
     
    				while (userAnswerInt != answer) {
     
    					System.out.println("What is 4 x 4 ?\n");
     
    					userAnswerInt = scan.nextInt();
     
    					if (userAnswerInt != answer) {
    						System.out.println("incorrect\n");
    					}
     
    				}
    				System.out.println("correct!");
     
    			}
     
    		}
    	}
     
    }


    --- Update ---

    here's a version without code comments as they might make it harder to read here -

    import java.util.Scanner;
     
    public class Loops {
     
    	public static void main(String[] args) {
     
    		int answer = 16;
     
    		Scanner scan = new Scanner(System.in);
     
    		System.out.println("What is 4 x 4 ?\n");
     
    		int userAnswerInt = 0;
    		userAnswerInt = scan.nextInt();
     
    		if (userAnswerInt == answer) {
    			System.out.println("correct");
    		} else {
     
    			System.out.println("Incorrect\n");
    			String userContinue = null;
     
    			System.out.println("Would you like to continue? Y/N \n");
     
    			String dummy = scan.nextLine();
     
    			userContinue = scan.nextLine();
     
    			String continueAnswer = "y";
    			if (userContinue.equalsIgnoreCase(continueAnswer)) {
     
    				while (userAnswerInt != answer) {
     
    					System.out.println("What is 4 x 4 ?\n");
     
    					userAnswerInt = scan.nextInt();
     
    					if (userAnswerInt != answer) {
    						System.out.println("incorrect\n");
    					}
     
    				}
    				System.out.println("correct!");
     
    			}
     
    		}
    	}
     
    }


  2. #2
    Crazy Cat Lady KevinWorkman's Avatar
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    5,424
    My Mood
    Hungover
    Thanks
    144
    Thanked 636 Times in 540 Posts

    Default Re: Splitting up main method / class

    This code doesn't seem all that complicated, so I don't see a problem keeping it in main. If you just want to practice, you could start by splitting up the different steps into separate methods.
    Useful links: How to Ask Questions the Smart Way | Use Code Tags | Java Tutorials
    Static Void Games - Play indie games, learn from game tutorials and source code, upload your own games!

  3. #3
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    5,520
    My Mood
    Mellow
    Thanks
    215
    Thanked 698 Times in 680 Posts

    Default Re: Splitting up main method / class

    IMO, a better next step to improve your skills would be to separate the main() method into multiple methods, including a constructor. This will move you from running an entire program in the main() method to defining the program as a class with a constructor, instance variables, and methods that perform the same function as the program contained in the main() method. The result of this will be a main() method of one or two lines, and that's where you need to be before starting GUI programming.

    If you'd like to pursue this approach and don't know how, come back.

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

    Default Re: Splitting up main method / class

    You are correct that you should do it in a class instead of your main. There is a very simple solution which most beginners overlook: Loops IS a class.
    This means that you create a constructor for the Loops class, move your code from your main to your Loops constructor, initialize a new Loops object in your main, and all the code will operate the exact same way.
    Here is an example. This code:
    public class Example {
    	public Example() {
    		System.out.println("Example");
    	}
     
    	public static void main(String[] args) {
    		new Example();
    	}
    }
    would do the exact same thing as this:
    public class Example {
    	public static void main(String[] args) {
    		System.out.println("Example");
    	}
    }
    There are many, many advantages to doing the first one, but those advantages will not be obvious for your example.
    Now, you can consider moving some of your functional code into methods, which you can call. Your code isn't very complex, so it can be difficult to split it up. However, what you could do is this:
    create a method: promptAndCheck() which does the code for prompting the question and checking the answer. You can make your Scanner an instance variable, and the promptAndCheck() method could have two parameters: String question, and int answer, and would return a boolean result, determining whether or not your answer was correct.
    So your method would look like this:
    public boolean promptAndCheck(String question, int answer) {
    	System.out.println(question);
    	// get user input
    	// compare the user input to the answer
    	if(correct) {
    		System.out.println("correct!");
    		return true;
    	}
    	else {
    		System.out.println("incorrect\n");
    		return false;
    	}
    }
    You can then have a while loop which calls that method. As long as the method returns false, ask the user if they want to continue. If the method returns true, exit the program like you already 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/

  5. #5
    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 GregBrannon View Post
    IMO, a better next step to improve your skills would be to separate the main() method into multiple methods, including a constructor. This will move you from running an entire program in the main() method to defining the program as a class with a constructor, instance variables, and methods that perform the same function as the program contained in the main() method. The result of this will be a main() method of one or two lines, and that's where you need to be before starting GUI programming.

    If you'd like to pursue this approach and don't know how, come back.
    Cheers Greg, that sound's exactly like what I was trying to say. I know Kevin's right and that it's not very complex, but it's about the learning as much as the practicality.

    But yes, I'm not too sure how I would go about splitting this program up into separate classes. I'm trying to think of the separate elements that are involved in it;

    fixed answer
    question
    Scanning lines for strings / integers
    if loop that checks if the answer is correct, then the else if it isn't
    question to user if they want to continue
    user input
    if statement that checks if the user has opted to continue....


    I'm not sure if this is the thought process that would be employed or not, seem's like I'm just writing the program's functions out in text!

    cheers

  6. #6
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    5,520
    My Mood
    Mellow
    Thanks
    215
    Thanked 698 Times in 680 Posts

    Default Re: Splitting up main method / class

    Sorry for the delay. The paying job called.

    As others have said, this program - as it is - is fairly simple and may not be the best to use as a model for the next step I've described, but something useful can be done with it. Let's expand the description of it a bit and use that.

    Right now, this program:

    1. presents the user with one multiplication problem,
    2. gets the user's answer
    3. checks the user's answer
    4. presents results
    5. asks the user if another try is desired

    In your version, if the answer to #5 is yes, the same problem is presented, but imagine instead that a different problem is presented, maybe even using a different mathematical operation.

    Then the possible methods could be:

    1. define mathematical problem
    2. present problem to user
    3. get user's answer
    4. grade user's answer
    5. present results (perhaps include the correct answer or give another chance to answer)
    6. ask if another problem is desired
    7. if exiting, show user's overall grade

    Repeat 1 - 6 until the user wants to quit.

    Many of those steps can be reusable methods. This design would also turn a class you called "Loops" that doesn't actually do any looping into one that loops. Even so, I recommend you name the new version MathProblems or similarly so that the class' name accurately describes what it does.

    How would you like to proceed? You could rewrite what you have to do what I've described and then break it into methods, or you could start over and write the new class with new methods. You decide.

  7. The Following User Says Thank You to GregBrannon For This Useful Post:

    Scren (January 29th, 2014)

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

    Default Re: Splitting up main method / class

    Hey Greg, just off to work myself

    But yes, I was thinking about making it into one the generated a problem instead of it being hard coded. Could be a multiplication table, or basic mixed maths.

    I think that re writing it might be best, it would harm me to write thing's out again and changing the little that's there might be more trouble than it's worth...

    Hopefully I get some free time at work later.

    cheers

  9. #8
    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 GregBrannon View Post
    Then the possible methods could be.........

    Hey greg back from work (shifts suck...) and going to start this... I'm thinking that It would be best to start a project from scratch for it.
    You could rewrite what you have to do what I've described and then break it into methods, or you could start over and write the new class with new methods
    New I think's best...

    I'm reading through what aussiemcgr wrote as well - I'm am trying to 'atomise' the concept into different parts....

    I think that something slightly more customisable might be a similar maths questions program but based on the times table... So the user could specify which times table they wanted to practice, or just say 'all'. (not sure if having a command for 'all' makes it harder than it should be, and should be left to just 1 - 12 for now or not...)

    So the console would ask the user what times table to practice, the user would then input a number. The console would then ask the user questions from the relevant times table. I'm not sure whether it should ask the user whether they want to continue at the end of each go. And I'm not sure about any sort of 'score taking' at the moment either, perhaps this is a bit tricky I'm not sure.

    But basically the user sits there after starting the program and get's asked questions about the times table they selected.

    So to start with I guess I need to have something that will ask the user a question, and if the program is going to be separated into all separate classes then this would be 'InitialQuestion' In this class I would need to greet the user, ask them what times table they wanted to learn, and take input from the console for the answer.

    Then I would need a question class - a class that actually had the maths in it. I would need an array of 1-12 that would represent the times table and was chosen from by the user... Or perhaps it would be easier to just have the user define a variable that had a maximum range of
    num>0    num<13
    and use that.... the question would have to be in some kind of loop in order to keep asking different questions....

    So that's two classes at the moment - I'm not sure if the second class 'TimesTableQuestion' class would have to extend the InitialQuestion class in order to access the information given by the user...


    Hmmm... So that's where my thought train is at the moment!

  10. #9
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    5,520
    My Mood
    Mellow
    Thanks
    215
    Thanked 698 Times in 680 Posts

    Default Re: Splitting up main method / class

    What you propose is fine and will give you experience passing data and/or instructions between two classes, depending on how you imagine the MathsQuestion class will work and implement it.

    As you've described it, the first class will present the program, determine the user's desires for multiplication practice, and then present the problems generated by the second class. I imagine the first class will also periodically ask the user if more problems are desired and/or if the type of questions should change and modify the problems being given or exit the program.

    The program should also keep track of the user's score and report that on exiting. Scoring could be part of the second class or simply another method in the first class, or done in another class entirely. I'm thinking the first approach (part of the second class) makes more sense, but sometimes these ideas don't make complete sense until some coding is done and the design is better understood.

  11. #10
    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 sure if having a command for 'all' makes it harder than it should be, and should be left to just 1 - 12 for now or not...
    Not if your framework is designed "correctly".

    if the program is going to be separated into all separate classes then this would be 'InitialQuestion' In this class
    ...
    Then I would need a question class - a class that actually had the maths in it.
    ...
    So that's two classes at the moment - I'm not sure if the second class 'TimesTableQuestion' class would have to extend the InitialQuestion class in order to access the information given by the user
    Ok, let's talk about this. You could have a class just to prompt the user at startup, but that may not be necessary.
    For extendability, I would recommend an approach where you have two classes:
    1. Question - this class would be abstract, or an interface
    2. TimesTableQuestion - this class would extend Question (or implement it, if it is an interface)

    Why do I suggest this? What if you want to include different types of questions in the future? You could create a new class for that type of question and extend off of the existing Question class.

    Your questions should not be directly linked to one another. They should be created by some sort of "manager" (this can just be your main, or something similar). The manager would determine what the user wants to do, and create new TimesTableQuestion objects based on what they want. When the user responds to the answer, the manager then determines if another question should be created or not.
    Tell me how much of this makes sense to you.

    I would need an array of 1-12 that would represent the times table and was chosen from by the user... Or perhaps it would be easier to just have the user define a variable that had a maximum range of
    The second approach would probably be better. It's a waste of memory and resources to store that list. You can ask the user at runtime just by counting.
    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/

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

    Scren (January 31st, 2014)

  13. #11
    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
    Not if your framework is designed "correctly".

    Tell me how much of this makes sense to you.
    cheers mcgr - I guess that I'll have two classes then. So there'll be

    1 : Main Method
    2 : Question Class
    3 : TimesTableQuestion class

    I wasn't sure if the TimesTQuestion class would have to extend the Quest class or not - but I guess that it does because it need's access to the information that the user will put in response to the question? I'm not sure why this approach is better for 'extendibility' (I don't fully get the meaning of that word in this context)

    So 1 Main Method - This will run code from the other two classes

    2 - Question : You mention that the questions shouldn't be directly linked to one another... I'm not sure I follow this. There will be one question that starts off

    "Which time table would you like to practice. Enter a number 1 - 12"

    Then when the user enters the number the program will assign it to a variable and pass this to the TimesTableQuestion class (can you use variables between classes?) I think that's the only question that the program needs to ask the user....

    3 - TimesTableQuestion class - this will take the users selection (1-12) and multiply it by a random number between 1 and 12.... I guess that there will have to be some kind of variables called 'correct' and 'incorrect' that are tallied up and triggered each time an answer is given to the user... Not sure how this would go (if statement?) After each question I guess the user would have to choose whether to continue or not, or the program could be done from a for loop and set to run a set amount of times.... Either way, once the program had finished it would return the users score... Maybe ask them if they want another go I'm not sure.


    So I hope that gives a reflection of my understanding (or lack of!) look forward to hearing more

  14. #12
    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 wasn't sure if the TimesTQuestion class would have to extend the Quest class or not - but I guess that it does because it need's access to the information that the user will put in response to the question? I'm not sure why this approach is better for 'extendibility' (I don't fully get the meaning of that word in this context)
    It has nothing to do with "needing access to the user input" and everything to do with the purpose of inheritance. By making TimesTableQuestion extend Question, you are making it so that TimeTableQuestion "is-a" Question. By extendability, I mean: let's say later down the line you want to add the ability to ask History questions, so you create a HistoryQuestion class. If TimesTableQuestion and HistoryQuestion both extend Question, a "relationship" between the two exist. By that, I mean they both inherit from the same super class (the super class being: Question). If you design your main to handle Question objects abstractly, no significant design changes to your main will have to occur to accommodate you adding history questions to your program.
    Let me show you an example using a simple User/Admin account design. Let's say we have a structure like this:
    public class Example {
    	public static void main(String[] args) {
    		// A list of account objects. These could be UserAccounts or AdminAccounts, it doesn't matter
    		Account[] accountList = new Account[3];
    		accountList[0] = new UserAccount("User1","Pass1");	// Adding a UserAccount
    		accountList[1] = new AdminAccount("Admin","Pass2");	// Adding an AdminAccount
    		accountList[2] = new UserAccount("User2","Pass3");	// Adding another UserAccount
     
    		// Loop through the list and print their access
    		for(int i=0;i<accountList.length;i++) {
    			Account account = accountList[i]; // Retrieve the object as a general Account object, because we don't care what it "really" is
    			System.out.println(account.getUsername()+" has access: "+account.hasAccess()); // Prints out whether or not the user has access
    		}
    	}
    }
     
    public abstract class Account {
    	protected String username;
    	protected String password;
     
    	public String getUsername() {
    		return username;
    	}
    	public String getPassword() {
    		return password;
    	}
    	/**
    	 * Determines if the user has access. Implemented by the subclass
    	 */
    	public abstract boolean hasAccess();
    }
     
    public class UserAccount extends Account {
    	public UserAccount(String user, String pass) {
    		username = user;
    		password = pass;
    	}
     
    	public boolean hasAccess() {
    		return false; // UserAccount does not have access
    	}
    }
     
    public class AdminAccount extends Account {
    	public AdminAccount(String user, String pass) {
    		username = user;
    		password = pass;
    	}
     
    	public boolean hasAccess() {
    		return true; // AdminAccount does have access
    	}
    }
    This code will print out:
    User1 has access: false
    Admin has access: true
    User2 has access: false

    Now, let's say we want to extend this design to include another type of Account which doesn't have access. Since inheritance allows us to make our program more "extendable", this is all that needs to change:
    public class Example {
    	public static void main(String[] args) {
    		// A list of account objects. These could be UserAccounts, ViewerAccount, or AdminAccounts, it doesn't matter
    		Account[] accountList = new Account[4];
    		accountList[0] = new UserAccount("User1","Pass1");	// Adding a UserAccount
    		accountList[1] = new AdminAccount("Admin","Pass2");	// Adding an AdminAccount
    		accountList[2] = new UserAccount("User2","Pass3");	// Adding another UserAccount
    		accountList[3] = new ViewerAccount("Viewer1","Pass4");	// Adding a ViewerAccount -- this the only new line we need to make our main to include the new ViewerAccount
     
    		// Loop through the list and print their access
    		for(int i=0;i<accountList.length;i++) {
    			Account account = accountList[i]; // Retrieve the object as a general Account object, because we don't care what it "really" is
    			System.out.println(account.getUsername()+" has Access: "+account.hasAccess()); // Prints out whether or not the user has access
    		}
    	}
    }
     
    public abstract class Account {
    	protected String username;
    	protected String password;
     
    	public String getUsername() {
    		return username;
    	}
    	public String getPassword() {
    		return password;
    	}
    	/**
    	 * Determines if the user has access. Implemented by the subclass
    	 */
    	public abstract boolean hasAccess();
    }
     
    public class UserAccount extends Account {
    	public UserAccount(String user, String pass) {
    		username = user;
    		password = pass;
    	}
    	public boolean hasAccess() {
    		return false; // UserAccount does not have access
    	}
    }
     
    public class AdminAccount extends Account {
    	public AdminAccount(String user, String pass) {
    		username = user;
    		password = pass;
    	}
    	public boolean hasAccess() {
    		return true; // AdminAccount does have access
    	}
    }
     
    /**
     * This is the new Account type we create
     */
    public class ViewerAccount extends Account {
    	public ViewerAccount(String user, String pass) {
    		username = user;
    		password = pass;
    	}
    	public boolean hasAccess() {
    		return false; // ViewerAccount does not have access
    	}
    }
    This new code will print out:
    User1 has access: false
    Admin has access: true
    User2 has access: false
    Viewer1 has access: false

    Tell me if you understand that much, and we'll continue with your other questions after you 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/

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

    Default Re: Splitting up main method / class

    just going to read through that post, this is what I started with (before I delete it...)

    import java.util.Scanner;
     
    public class UserQuestion {
     
    	public UserQuestion() {
     
    		System.out.println("Which timetable would you like to practice? Enter a value between 1 and 12");
     
    		Scanner scan = new Scanner(System.in);
     
    		int tableNum = scan.nextInt();
     
    		String dummy = scan.nextLine();
     
    		if ((tableNum < 1) || (tableNum > 12)) {
    			System.out.println("Please enter a value between 1 and 12");
     
     
     
     
    		}
     
    	}
     
    }

  16. #14
    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, I would recommend a different, method-driven approach.

    Imagine an abstract Question class.
    What traits would ALL types of questions have? Off the top of my head, I can think:
    1. The question text
    2. The question's answer
    So, all Questions should have instance variables:
    1. String question;
    2. String answer;
    Now, what things should a question do?
    1. Ask the user the question.
    2. Check the answer (some sort of correct/incorrect result should be returned)
    So, all Questions should have these two methods:
    1. void askQuestion();
    2. boolean checkAnswer(String reply); -- Where "reply" is the user's reply to the question

    Now, where does the "manager" (or, the main in your setup) come into play here? Well, the "manager" should:
    1. Create a new Question object (perhaps your UserQuestion should have a constructor which accepts the question and answer Strings to set)
    2. Invoke the Question.askQuestion() method on the newly created Question object to prompt the user
    3. Read the result the user supplied
    4. Invoke the Question.checkAnswer(result); method on the newly created Question object to see if the answer the user supplied was correct
    5. Prompt the user if they want to keep going/exit the program/loop back to Step #1
    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. #15
    Member
    Join Date
    Dec 2013
    Posts
    51
    Thanks
    11
    Thanked 0 Times in 0 Posts

    Default Re: Splitting up main method / class

    Right OK I've read through the example that you've posted:

    I'm not really that au fait with the arrays being used in the for loop, If I look at each bit individually it kind of makes sense but then when I look at that bit together it goes out of focus.

    There's an array of accounts, instantiated by

    accountList[0] = new UserAccount("User1","Pass1");	// Adding a UserAccount
    accountList[1] = new AdminAccount("Admin","Pass2");	// Adding an AdminAccount
    accountList[2] = new UserAccount("User2","Pass3");	// Adding another UserAccount

    So that's created an array of accounts. accountList[1] would be the AdminAccount, and it's access would be the default 'true'.

    Then It moves onto the for loop - I get the set up of it, that i will increase until it reaches the maximum value of the arrays length.

    Account account = accountList[i];

    That's not really making sense to me for some reason. I know the comment say's "Retreive the object as a general Account", and I get that account's not specific... So that's assigning each iteration of i to a new account? (although I though that we'd created new accounts when the array list was initially created.)

    Then at the bottom of the page we've got the three classes - Account, UserAccount and AdminAccount. User and Admin extend Account, because they are both types of account. They both have hasAccess(); methods that over write the hasAccess(); methods in the Account class. This is in the accounts class because all account's will either have access or they won't. As both the UserAccount and AdminAccount extend the Account they have access to their variables... and these are over written in the different classes. Boolean values are changed to false in user and true in admin.

    That's kind of where I'm at with that I guess.... My email pinged but I wanted to finish this first

    nice one

    --- Update ---

    cheers for #14 - just having a go at setting up the abstract question class, I'll post the code up soon

    --- Update ---

    Hmm I'm really tired so I'm going to try and re approach this tomorrow, here's the little I've just written though

    just the question class... I'm trying to think how to do them... If the class is going to be open to future interpretation then there can't be anything hard coded into it. And I get other classes will extend this one and override it's methods

     
    import java.util.Scanner;
     
     
    public abstract class Question {
     
    	protected String questQuestion;
    	protected String questAnswer;
     
    	public String askQuestion(String questQuestion) {
     
    		this.questQuestion = questQuestion;
    		return questQuestion;
    	}
     
    	public String getAnswer(){
    		return questAnswer;
    	}
     
     
    }

  18. #16
    Member
    Join Date
    Dec 2013
    Posts
    51
    Thanks
    11
    Thanked 0 Times in 0 Posts

    Default Re: Splitting up main method / class

    Hmm I'm looking at this again and I'm not sure what I'm doing to be honest (perhaps it was a bit of a leap....)

    I've written a class called Question and I've extended it to TablesTest..... I'm going to think aloud a bit here (hopefully stupid isn't contagious) so my thought's and understandings are clearer ;

    Question:

     
    import java.util.Scanner;
     
     
    public abstract class QuestionAnswer {
     
    	protected String question;
    	protected String answer
    	;
     
    	public String askQuestion(String questQuestion) {
     
    		this.question = questQuestion;
    		return questQuestion;
    	}
     
    	public void getAnswer(){
     
    		Scanner scan = new Scanner(System.in);
     
     
     
     
    	}
     
     
    }

     
    public class TablesTest extends QuestionAnswer {
     
    	public String askQuestion() {
     
    		question = "Which times table would you like to practice? Input a number from 1 to 12";
     
    		return question;
    	}
     
     
            // ?
    	public int getAnswer() {
     
    		TablesAnswer = scan.nextInt();
     
    		return TablesAnswer;
    	}
    }


    So the tables askQuestion overwrites the Question class question... System.out.println(timesTable.askQuestion()); work's and returns the relevant question to the console....

    So know I need to create a method that will take an int input, and it has to be user specified rather than being coded in... I'm struggling to relate this to the Questions answer at the moment. I can't put in any question into the Question class as It's abstract and doesn't have anything to question about... Can I put a scanner in there? But I don't know what to scan! A history test would take a String where as a maths would take an int, so even though all questions (in this context, not philosophically...) have answers they don't have them consistently... I'll create a blank method in Question I guess just to show it's there. Or maybe answer is a separate class, although you can only have one superclass, so I guess that's not really possible. All I know for sure is that it need's input, so I've created a Scanner in that method.

    Also - In the Question method I created the variables Question and Answer as Strings, I guess that's wrong as well because the answer is going to be an int in the TablesTest class...

    Right, well I'm stuck at this point, I'm trying to move on and work thing's out but I feel that the design's probably awful.... Hopefully the above highlight's any understanding and whether or not something else would be more applicable to work on at the moment

  19. #17
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    5,520
    My Mood
    Mellow
    Thanks
    215
    Thanked 698 Times in 680 Posts

    Default Re: Splitting up main method / class

    I'll help if I understand what you're trying to do, but I'm not sure at this point. Write which classes you plan to use with a short description of what each one will do.

    Personally, I think the abstract class idea is a bit of a giant step for you at this point. You haven't even used multiple classes in a single program yet. I recommend stepping back a bit and picking 2 or 3 simple classes, describe what they do, and then work forward from there.

    But in the end, do what you want. Please describe it accurately so we can help with it.

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

    Default Re: Splitting up main method / class

    The main priority with this is learn, so If someone was to say "you'd be much better off writing a program that list's farm yard animal's" then I'd go off and do that, I don't have any criteria to meet in regards to the final program.

    Personally, I think the abstract class idea is a bit of a giant step for you at this point. You haven't even used multiple classes in a single program yet
    Yes, probably right (although thank's aussiemcgr for the assistance). I'm happy to have a go at thing's but one of the reason's I've shown my thought process is so that people helping can see whether its a bit of a leap for me or whether I'm pretty much there I just need a tip, because I have no experience or reference point on the subject. This is my first program really, I mean I've written out some loops and stuff, but this would have been the first functional-ish thing that I'd made (if that makes sense). I'm not hung up on finishing this, like I said, I just want to learn to if that's a step back for two forwards then I'm cool with that. I obviously need prompting with thing's from others because I'm learning, but if it get's near the stage of needing people to put pretty much full code up for me I guess it defeat's the point somewhat!

    OK so my 'design process' is currently as follows (going on from previous advice about extension, although like you say I might be stretching here....)

    Classes:

    1 - Main method

    This is just going to be running the code from the other classes

    2 - QuestionAnswer

    Basically the blue print for a question and an answer... The question would then be defined by the relevant class to suit the topic. The answer has confused me, if it's (basic times table) maths then it would want to be an int, if it was something like geography then it would have to be a String. I feel like I should be instantiating all relevant method's in the Q&A class and then overriding them in others.... Not sure why.

    3 - TimesTable

    This is what 'defines' the program as the other stuff is abstract. The times table class would over ride the Question and ask the user to input a value representing the times table that they want to practice. I can do this with the String part of the Question, but the answer confuses me. I need a scanner because it's input into the console, but I don't know whether the scanner should be implemented in the Q&A class (because all questions will have user input) or the specific class... Also, this is the answer to the set up question rather than the specific 1 x 2 or whatever questions, so I'm not sure if that changes anything on the design front...

    But in the end, do what you want. Please describe it accurately so we can help with it.
    Cheers greg, as above it's purely just for self learning purposes, there's no goal other than that at the moment...

    Hope the above is informative

  21. #19
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    5,520
    My Mood
    Mellow
    Thanks
    215
    Thanked 698 Times in 680 Posts

    Default Re: Splitting up main method / class

    I don't see what's holding you back, so I'm going to flesh out the assignment a bit and then suggest you get going:

    1. Describe the program to the user (times table practice)
    2. Ask the user which table to practice, 1 - 9 or all
    3. Present the user with RANDOM problems from the chosen table in blocks
    4. Present the results after each block and ask:
    5. Continue?
    5.A. If continue, use the same or a different table (1 - 9) or all and present another block of the desired problems
    5.B. If not continue, quit and exit
    6. On exit, present the total results in the form:
    Table   Attempts    Correct
    -----   --------    -------
      1        #           #
      2        #           #
      3        #           #
     etc.    etc.        etc.
    and exit. Use 2 or 3 classes as has been discussed throughout this topic and ONLY non-static methods except for the main() method. The main() method should be no more than 2 statements, 1 statement is preferred (extra credit).

    Number 6 may be too challenging at this point, but we'll cross that bridge when you get there.

    Get going. Ask questions as needed.

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

    Default Re: Splitting up main method / class

    The main priority with this is learn, so If someone was to say "you'd be much better off writing a program that list's farm yard animal's" then I'd go off and do that, I don't have any criteria to meet in regards to the final program.
    Ok, this gives me an idea. Tell me what you think. Let's temporary table your current project idea, and attempt to do something just as simple, but I'll provide you with properly defined goals and objectives, so it may be easier for you to understand the concepts we are discussing.
    We will do this in two parts. The first part will contains some very minimal goals. After that, we will do the second part, where we will just a little bit of extra functionality to the project.

    Project Description - Part 1:
    Let's create a small Farm program, where the user enters the name of an animal, that animal is added to the farm, and the program responds with sound (in text, not sound files or anything) that the animal makes.
    This particular Farm will have 3 animals: a pig, a cow, and a sheep. A pig says: "oink", a cow says: "moo", and a sheep says: "baa". Easy enough.
    The Farm should keep track of the number of each type of animal the user requests.
    The Farm should prompt the user, asking what animal they would like added to the farm. The prompt should also provide the user with an "exit-case", meaning: a way to terminate the program.
    The Farm should read the user's input, and create the animal that the user wants.

    Ok, so the console output would read similar to this:
    Pig: 0, Cow: 0, Sheep: 0
    What type of animal do you want created? Enter -1 to end the program.
    - pig
    The Pig says "oink".
    Pig: 1, Cow: 0, Sheep: 0
    What type of animal do you want created? Enter -1 to end the program.
    - cow
    The Cow says "moo"
    Pig: 1, Cow: 1, Sheep: 0
    What type of animal do you want created? Enter -1 to end the program.
    - sheep
    The Sheep says "baa"
    Pig: 1, Cow: 1, Sheep: 1
    What type of animal do you want created? Enter -1 to end the program.
    - cow
    The Cow says "moo"
    Pig: 1, Cow: 2, Sheep: 1
    What type of animal do you want created? Enter -1 to end the program.
    - -1

    If you think you want to give this a try, let's discuss the design you would want. Without doing any coding, tell me the different classes you think you would need, the methods you think you need in each class, and the instance variables you think you need in each class.
    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/

  23. #21
    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 see what's holding you back
    Really???

    Quote Originally Posted by aussiemcgr View Post
    Project Description - Part 1:
    Let's create a small Farm program.....
    Ha ok then let's try this....

    Parts that I think I'm going to need

    Main method - no explanation

    Animals class -

    OK I think this is going to be the parent class, and will contain method's to be implemented and over ridden by the others. Method's in this class will be ones that can extend to all animals. So all animals have a type.
    In the example its

    type : pig
    type : cow
    type : sheep
    could be type : horse etc...

    so the method for type would be (I think)


    public String animalType(){
     
    	}
    problem here is that I'm no sure what to do with these methods in the abstract classes... Or if I should just be using constructors and putting everything within them (like in the user / admin account's example you posted earlier) I've started playing around with code for a bit then without thinking, back to this....

    All animals make a sound, so that would also be in the abstract class.

    cow : moo
    sheep : baa
    pig : oink
    could be horse : neigh etc.... (not sure why I'm using horse...)

    We could do other thing's like colour, but there wouldn't be much point for this...

    So :

    Abstract Class Animal
    Methods :
    AnimalType
    AnimalSound
    exit method?





    Then we move onto the counting. I'm vaguely aware of the concepts behind this - the variables for counting need to be made at class level....? So that each time a class is instantiated it increments the class variable. Might be

    public static class Cow = Cow;

    Although that's probably pretty off point... But this amount variable would have to be declared in each class individually, although every animal does have an amount (even if it's zero) so maybe it needs to be in the Animals class and over ridden...

    Class eg Sheep

    Over ride Type method
    Over ride Sound method

    Create a variable that will count the amount of times that the class is implemented

    And then the user needs a way to exit / end the program / tell the program that they've created all of the animals they want.... Not sure if there would be a program on it's all, ProgramControl perhaps - and within it an if statement that read the user input... Though maybe it would have to be in the Animals class because it needs to be checked each time an animal is created.

    It's also printing out the amount of animals created after each creation - so that count / array would have to be able to access the variables from the other classes as well to print them out....


    I'll stop here before I start making circles

    thanks

  24. #22
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    5,520
    My Mood
    Mellow
    Thanks
    215
    Thanked 698 Times in 680 Posts

    Default Re: Splitting up main method / class

    Sorry if I offended. Good luck!

    aussiemcgr's proposed path is excellent and should do you well.

  25. #23
    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 GregBrannon View Post
    Sorry if I offended. Good luck!
    No offence, I'm just surprised at my incapacity being brought into question!

  26. #24
    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, let's not deal with an abstract Animal class right now. We will do that in Part 2.

    For right now, let's create a class for each animal, without a parent class for them to extend from. We will do it this way because I think it will make the use of an abstract class in Part 2 make more sense to you.
    Do not think about the main right now. I will explain how to implement that later.
    The design I had in mind was something like this (for reference, I'll use * to indicate an instance variable and - to indicate a method):
    Farm Class
    * int pigCount
    * int cowCount
    * int sheepCount
    - promptUser()
    - createAnimal(String type)

    Pig Class -- This would have a constructor which accepts a String, to set the sound variable
    * String sound
    - getSound()

    Cow Class -- This would have a constructor which accepts a String, to set the sound variable
    * String sound
    - getSound()

    Sheep Class -- This would have a constructor which accepts a String, to set the sound variable
    * String sound
    - getSound()

    What do you think about this design?
    We do not count the animals in the classes for the animals. We count them in the Farm class. The Farm class creates the animals, and keeps track of how many of them it has created. The animal classes do not need a "type" attribute, since the "type" of the animal is determined by the class. By that, I mean: you can't create a Cow with the Pig class, so you know an instance of the Pig class can only be a Pig.
    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/

  27. #25
    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
    Ok, let's not deal with an abstract Animal class right now. We will do that in Part 2.
    cool.

    * int pigCount
    * int cowCount
    * int sheepCount
    - promptUser()
    - createAnimal(String type)

    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.

    So we'll put the exit option into version 2 as well? cool cool....

    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?


    I'm not sure if this is the kind of thing
    If(userInput == CowAnimal){
    cowCount++;
    CowClass cow[cowCount] = new CowClass;
    }

    Still confuses me how everything will link in, but I think that'll click when I see it...


    Pig Class -- This would have a constructor which accepts a String, to set the sound variable
    * String sound
    - getSound()


    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") ?

    I'm really unsure how the scanner should be integrated into all of this - though the only place I can see it being is in the Farm Class.

     
    public void promptUser(){
     
    System.out.println("Which farm animal would you like to create?");
     
    Scanner scan = new Scanner(System.in);
     
    String animalType = scan.nextLine();
     
     
    if (animalType == PigClass){
     
    PigCount++
    }elseif (animalType.ignoreCase == CowClass.ignoreCase
     
    }

    Not sure if that's how they would integrate... think I might have used method's that don't exist there as well (though there's a similar thing)

    Sound's good though, cheers

    --- Update ---

    Just had a bash at making the FarmClass -

     
    import java.util.Scanner;
     
    public class FarmClass {
     
    	int pigCount;
    	int cowCount;
    	int sheepCount;
     
     
     
    	public void promptUser() {
     
    		System.out.println("what kind of animal would you like to create?");
     
    	}
     
    	public String createAnimal(String animal) {
     
    		Scanner scan = new Scanner(System.in);
     
    		animal = scan.nextLine();
     
    		return animal;
     
    	}
     
    }

    What's still throwing me is how to link these together.... The createAnimal class - I'm assuming that it should be taking input from the user and incrementing the pigCount... I've tried using a Scanner for this but I'm not sure that it's the right way, or whether a scanner should be inside a method like that.

Page 1 of 3 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