6 Replies - 747 Views - Last Post: 06 February 2013 - 08:13 PM Rate Topic: -----

#1 Jpopto  Icon User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 31
  • Joined: 04-April 12

Making top down program into different classes

Posted 05 February 2013 - 09:40 PM

I have a code that works fine but I'd like to break it up into three different classes. I'm not good with returning and instantiating classes.
import java.util.Random;

	public class MathTest
	{
public static void main (String [] args)
   {

	  //local constants
	    final int RANGE         = 10;    //# of diff values to create
	    final int NUM_QUESTIONS = 5;
	    final int QUIT          = 2;

	  //local variables
	    int num1;            		  // 1st number
	    int num2;   				  // 2nd number
	    int answer;                   // answer to the addition problem
	    int userSelection;            // user selects to take test or to quit
	    int numCorrect;               // number of correct answers
	    float testScore;                // test score of user in percentage
        Random gen = new Random();    // Random class to generate random numbers

			   Library myLib = new Library ();

		 //Display test menu and input user choice
		   System.out.print("\n\n                          Simple Math Tests Made Easy\n\n" +
		                            "                                1. Take a Test\n" +
		                            "                                2. Quit\n\n" +
		                            "                                Enter Choice: ");
		   userSelection = Keyboard.readInt();

		 //WHILE (user selection is take test)
		   while(userSelection != QUIT)

		         {

		 //Clear the screen
		   myLib.clrscr();

		 //Init number correct to 0
		   numCorrect = 0;

		 //FOR (Each of the 5 questions)
		   for (int count = 0; count < NUM_QUESTIONS; count++)
		   {
		 //Generate two random singal digit numbers
		   num1 = gen.nextInt(RANGE);
		   num2 = gen.nextInt(RANGE);

		 //Display the equation and input user answer
		   System.out.print("\n\n\n\n\t\t\t\t\t\t\t\t" +
		                                   num1 + " + " + num2 + " = ");
		   answer = Keyboard.readInt();

		 //IF (answer is correct)
		   if (answer == num1 + num2)
			{

		 // Display Correct
		   System.out.println ( " CORRECT  " );

		 //Add 1 to number correct
		   numCorrect++;

		}

		 // ELSE Display answer is Incorrect
			else
		 	 {
				 System.out.println ( " INCORRECT " );
			 }

		//Pause the Screen
		  myLib.pause();

	    //Clear the screen
		  myLib.clrscr();


		}

		// calculate the test score average
		testScore = ( (float) numCorrect / NUM_QUESTIONS) * 100;

		//Output the results
		System.out.print("\n\n                          RESULTS OF THE TEST \n\n" +
				  		                    "                                "    +
				  		                    "                                " +
		  		                            "                                          %" + testScore  );
		System.out.print("\n\n       ");

		//Pause the Screen
		  myLib.pause();

		 //Clear the screen
		  myLib.clrscr();

		  //Display test menu and input user choice
		  	System.out.print("\n\n                          Simple Math Tests Made Easy\n\n" +
		  		                            "                                1. Take a Test\n" +
		  		                            "                                2. Quit\n\n" +
		  		                            "                                Enter Choice: ");
		   userSelection = Keyboard.readInt();



		      }



		   } //end main method

		} //end MathTest





I've written a pseudocode based on my understanding of creating classes but honestly don't know how to break it down.

here's my pseudocode

/************************************************************************
*BEGIN Create Test
* Set num correct to 0
* FOR (Each question to generate)
* create single digit random number
* create second single digit random number
* display equation and prompt user for answer
* IF (user's answer is correct)
* display "correct" message
* add 1 num correct
* ELSE
* display "incorrect message
* END IF
* END FOR
* Calculate test score
* Return test score
*END Create Test
*************************************************************************/

/********************************************************
*
* BEGIN Display Menu
* Display user menu
* prompt user for selection
* return user selection
* END Display Menu
*
*********************************************************/

/************************************************************************
*
*BEGIN Main
* call menu method to return user's choice menuInput for user
* WHILE menuInput is not QUIT
* Set number correct to 0
* Call method to create test and return test score
* Clear screen
* Display test score
* call menu method to return user's choice menuInput for user
* END IF
*END Main
**************************************************************************/

Is This A Good Question/Topic? 0
  • +

Replies To: Making top down program into different classes

#2 jon.kiparsky  Icon User is offline

  • Beginner
  • member icon


Reputation: 11021
  • View blog
  • Posts: 18,804
  • Joined: 19-March 11

Re: Making top down program into different classes

Posted 05 February 2013 - 10:21 PM

I don't think I can help much with this particular program, but in general, you can think of each class as creating a little server program, which waits for input on various channels (public methods) and responds to it, possibly by doing some internal reckoning and figuring (private methods).


So if you think of it that way, each of these classes should have some defined methods which the world can call on: start by writing skeletons for those. So the second (and shortest) of your classes) might hang out a shingle offering to display a menu to the user, prompt for a response, and return the response.

Okay, well that's really just one public method: it accepts a list of options and a list of acceptable responses, and it asks the user to enter an acceptable response. If the response is not acceptable, it scolds the user and asks again. When it gets an acceptable response, it returns that response to the caller.

There's a little bit of programming to do here, but since it's all self-contained it's not too hard to do.

You can test this easily enough by just generating some nonsense "question" and answers (you're going to have to make decisions about the formats for both) and shooting them at your new DisplayMenu class until it seems to be acting responsibly.

Obviously, you can do the same for other classes. (but notice that this:

* display equation and prompt user for answer
* IF (user's answer is correct)
* display "correct" message
* add 1 num correct
* ELSE
* display "incorrect message
* END IF

looks a lot like what you've just learned how to build. Can you use that DisplayMenu class to do that work? Does that make life easier? (the answer is yes in both cases)
Was This Post Helpful? 1
  • +
  • -

#3 natecat  Icon User is offline

  • D.I.C Head

Reputation: 57
  • View blog
  • Posts: 233
  • Joined: 19-December 11

Re: Making top down program into different classes

Posted 05 February 2013 - 10:22 PM

Well, I recommend you read this: http://www.tutorials...ect_classes.htm It should help you a lot with your problem.
Was This Post Helpful? 1
  • +
  • -

#4 Jpopto  Icon User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 31
  • Joined: 04-April 12

Re: Making top down program into different classes

Posted 05 February 2013 - 10:28 PM

View Postjon.kiparsky, on 05 February 2013 - 10:21 PM, said:

I don't think I can help much with this particular program, but in general, you can think of each class as creating a little server program, which waits for input on various channels (public methods) and responds to it, possibly by doing some internal reckoning and figuring (private methods).


So if you think of it that way, each of these classes should have some defined methods which the world can call on: start by writing skeletons for those. So the second (and shortest) of your classes) might hang out a shingle offering to display a menu to the user, prompt for a response, and return the response.

Okay, well that's really just one public method: it accepts a list of options and a list of acceptable responses, and it asks the user to enter an acceptable response. If the response is not acceptable, it scolds the user and asks again. When it gets an acceptable response, it returns that response to the caller.

There's a little bit of programming to do here, but since it's all self-contained it's not too hard to do.

You can test this easily enough by just generating some nonsense "question" and answers (you're going to have to make decisions about the formats for both) and shooting them at your new DisplayMenu class until it seems to be acting responsibly.

Obviously, you can do the same for other classes. (but notice that this:

* display equation and prompt user for answer
* IF (user's answer is correct)
* display "correct" message
* add 1 num correct
* ELSE
* display "incorrect message
* END IF

looks a lot like what you've just learned how to build. Can you use that DisplayMenu class to do that work? Does that make life easier? (the answer is yes in both cases)


I think I'm mostly having a hard time understanding just how to return values and use them in different classes. Can't seem to grasp it, and yeah I am a total n00b . For example, would my DisplayMenu class look something like this
import java.util.Random;

public class TestMenu 
{
/********************************************************
*
*
*
*
*
*
*
*
*
* BEGIN Display Menu
*    Display user menu
*    prompt user for selection
*    return user selection
* END Display Menu
*
*********************************************************/

public static int GetUserSelection (int userSelection)
{

        			//Display test menu and input user choice
					System.out.print("\n\n                          Simple Math Tests Made Easy\n\n" +
							                   "                                1. Take a Test\n" +
							                   "                                2. Quit\n\n" +
							                   "                                Enter Choice: ");

		           userSelection = Keyboard.readInt();

		   	       return userSelection;
}
}


and by doing this can I instantiate TestMenu in another class and use it as an integer?
Was This Post Helpful? 0
  • +
  • -

#5 jon.kiparsky  Icon User is offline

  • Beginner
  • member icon


Reputation: 11021
  • View blog
  • Posts: 18,804
  • Joined: 19-March 11

Re: Making top down program into different classes

Posted 05 February 2013 - 10:36 PM

If that all compiles, the return type tells me that you can treat a call to that as an int, yes.
Taking userSelection as a parameter is incorrect, though. You don't need the calling class to submit an integer.
You might want to allow the calling class to provide the String - then the display class is simply the agent for the caller. It waits around until someone asks it to display a thing, then it displays that thing and returns the response. And if you want to allow the Display class to ensure that the return value is reasonable, you might want the calling class to inform the Display class of what range of responses it should accept. One way to do that would be to let the method signature be this:

public static int GetUserSelection (String question, String[] answers)

Now you can display the question, and the possible answers (Display can put numbers in front of them - which is a nice convenience) and by counting the number of entries in the answers array you can know whether a reasonable response has been provided.
Was This Post Helpful? 1
  • +
  • -

#6 Jpopto  Icon User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 31
  • Joined: 04-April 12

Re: Making top down program into different classes

Posted 06 February 2013 - 08:02 PM

View Postjon.kiparsky, on 05 February 2013 - 10:36 PM, said:

If that all compiles, the return type tells me that you can treat a call to that as an int, yes.
Taking userSelection as a parameter is incorrect, though. You don't need the calling class to submit an integer.
You might want to allow the calling class to provide the String - then the display class is simply the agent for the caller. It waits around until someone asks it to display a thing, then it displays that thing and returns the response. And if you want to allow the Display class to ensure that the return value is reasonable, you might want the calling class to inform the Display class of what range of responses it should accept. One way to do that would be to let the method signature be this:

public static int GetUserSelection (String question, String[] answers)

Now you can display the question, and the possible answers (Display can put numbers in front of them - which is a nice convenience) and by counting the number of entries in the answers array you can know whether a reasonable response has been provided.


So this is what I tried to do although I know it's probably really wrong but am I in the right direction? Can you see my errors.

This is my test menu
import java.util.Random;

public class TestMenu
{
/********************************************************
*
*
*
*
*
*
*
*
*
* BEGIN Display Menu
*    Display user menu
*    prompt user for selection
*    return user selection
* END Display Menu
*
*********************************************************/



			int userSelection;

					public String DisplayMenu ()
					{
						String result;

        			//Display test menu and input user choice
					result = ("\n\n                          Simple Math Tests Made Easy\n\n" +
							                   "                                1. Take a Test\n" +
							                   "                                2. Quit\n\n" +
							                   "                                Enter Choice: ");

					return result;

				    }
					public int GetUserStuff (int userSelection)
					{
		           userSelection = Keyboard.readInt();

		   	       return userSelection;
			       }
}


This is the TestMain

import java.util.Random;

public class TestMain
{

/************************************************************************
*
*
*
*
*
*
*
*
*
*BEGIN Main
*   call menu method to return user's choice menuInput for user
*   WHILE menuInput is not QUIT
*      Set number correct to 0
*      Call method to create test and return test score
*      Clear screen
*      Display test score
*      call menu method to return user's choice menuInput for user
*   END WHILE
*END Main
**************************************************************************/

public static void main ( String [] args )
{

            //local constants
		    final int RANGE         = 10;    //# of diff values to create
		    final int NUM_QUESTIONS = 5;
		    final int QUIT          = 2;

		   //local variables
		    int num1;            		  // 1st number
		    int num2;   				  // 2nd number
		    int answer;                   // answer to the addition problem
		    int userSelection;            // user selects to take test or to quit
		    int numCorrect;               // number of correct answers
		    float testScore;              // test score of user in percentage

       Random gen = new Random();        // Random class to generate random numbers

        		Library myLib = new Library ();

        		TestMenu menu = new TestMenu ();

	         //WHILE (user selection is take test)
			   while( userSelection != QUIT)
			  {

			  //Init number correct to 0
		        numCorrect = 0;

			  CreateTest Test = new CreateTest ();

			  myLib.clrscr();

			  //Output the results
			  System.out.print("\n\n                          RESULTS OF THE TEST \n\n" +
			  				 	                    "                                "    +
			  				  	                    "                                " +
			  		  		                        "                                          %" + testScore  );
			  System.out.print("\n\n       ");


				
			  }

}
}



and this is the class to create the test

import java.util.Random;

/************************************************************************
*BEGIN Create Test
*   Set num correct to 0
*   FOR (Each question to generate)
*      create single digit random number
*      create second single digit random number
*      display equation and prompt user for answer
*      IF (user's answer is correct)
*         display "correct" message
*         add 1 num correct
*      ELSE
*         display "incorrect message
*      END IF
*   END FOR
*   Calculate test score
*   Return test score
*END Create Test
*************************************************************************/


public class CreateTest
{
		  private  final int RANGE         = 10;
		  private  final int NUM_QUESTIONS =  5;
		  private  final int QUIT          =  2;

//local variables
	private    int num1;            		  // 1st number
	private    int num2;   				  // 2nd number
	private    int answer;                   // answer to the addition problem
	private    int userSelection;            // user selects to take test or to quit
	private    int numCorrect;               // number of correct answers
	private    float testScore;                // test score of user in percentage
        Random gen = new Random();    // Random class to generate random numbers

			   Library myLib = new Library ();

   public int iniatialize ( int numCorrect)
   {
	//Init number correct to 0
    numCorrect = 0;

    return numCorrect;
}

	public int getNumbers ()
	{
     //FOR (Each of the 5 questions)
	   for (int count = 0; count < NUM_QUESTIONS; count++)
	   {
	 //Generate two random singal digit numbers
	 num1 = gen.nextInt(RANGE);
	 num2 = gen.nextInt(RANGE);

	 //Display the equation and input user answer
	 System.out.print("\n\n\n\n\t\t\t\t\t\t\t\t" +
	                                   num1 + " + " + num2 + " = ");
	 answer = Keyboard.readInt();
	return answer;
}


	//IF (answer is correct)


	if (answer == num1 + num2)
	{

	// Display Correct
	System.out.println ( " CORRECT  " );

	//Add 1 to number correct
	numCorrect++;

	}

	// ELSE Display answer is Incorrect
	else
	{
		System.out.println ( " INCORRECT " );
	}

      return answer;
	}

	public float getTestScore ()
	{
	// calculate the test score average
    testScore = ( (float) numCorrect / NUM_QUESTIONS) * 100;

    return testScore;
    }
}

Was This Post Helpful? 0
  • +
  • -

#7 jon.kiparsky  Icon User is offline

  • Beginner
  • member icon


Reputation: 11021
  • View blog
  • Posts: 18,804
  • Joined: 19-March 11

Re: Making top down program into different classes

Posted 06 February 2013 - 08:13 PM

Probably better if you try it out and figure out what's working about it and what isn't, and then try to work from there. When you run it, what happens? Was that what you expected? If not, try to explain that to yourself. Why did it do what it did, and how can you change it to be more like what you wanted?

Remember, it's very easy to follow a Java program: when you run it, it starts at the first line of main(), and goes to the end, and then exits when it runs out of things to do. That's pretty much it - dead simple.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1